Skip to content

Instantly share code, notes, and snippets.

@Olegas
Last active May 26, 2016 04:52
Show Gist options
  • Save Olegas/9143277 to your computer and use it in GitHub Desktop.
Save Olegas/9143277 to your computer and use it in GitHub Desktop.
iOS hover-click problem solution.
/**
* Solution for http://stackoverflow.com/questions/21786375/ios-7-hover-click-issue-no-click-triggered-in-some-cases
*/
$(document).ready(function(){
if (/* if this is not iOS */) {
return;
}
var $body = $('body');
function addPseudoHover() {
this.classList.add('ws-pseudo-hover');
}
function removePseudoHover() {
this.classList.remove('ws-pseudo-hover');
}
function uniq(item, index, array) {
return array.indexOf(item, index + 1) == -1;
}
function trimHoverBase(selector) {
return selector.substr(0, selector.indexOf(':hover')).trim();
}
function filterHoverSelectors(selector) {
return selector.indexOf(':hover') != -1;
}
function createBodyDelegate(hoverSelector){
$body.delegate(hoverSelector, 'mouseenter', addPseudoHover);
$body.delegate(hoverSelector, 'mouseleave', removePseudoHover);
}
function processMutationRecord(mutationRecord) {
var needRefresh = false;
if (mutationRecord.addedNodes) {
for(var i = 0, l = mutationRecord.addedNodes.length; i < l; i++) {
if (mutationRecord.addedNodes[i].nodeName == 'LINK') {
needRefresh = true;
break;
}
}
}
if (needRefresh) {
checkStylesheetSetDebonuced();
}
}
function checkStylesheetSet() {
var
allHoverSelectors = [],
allRules = [],
sheet, sheetCheckResult;
for(var i = 0, l = document.styleSheets.length; i < l; i++) {
sheet = document.styleSheets[i];
if (sheet.processed || sheet.rules.length === 0) {
continue;
}
sheetCheckResult = checkCSSRuleSet(sheet);
if (sheetCheckResult.rules.length > 0 && sheetCheckResult.selectors.length > 0) {
Array.prototype.push.apply(allHoverSelectors, sheetCheckResult.selectors);
Array.prototype.push.apply(allRules, sheetCheckResult.rules);
}
sheet.processed = true;
}
// selector replace
allRules.forEach(function(aRule){
aRule.selectorText = aRule.selectorText.replace(':hover', '.ws-pseudo-hover');
});
// фильтруем уникальные селекторы, сорздаем делегатов на body
allHoverSelectors.map(trimHoverBase).filter(uniq).forEach(createBodyDelegate);
}
var checkStylesheetSetDebonuced = checkStylesheetSet.debounce(420);
function checkCSSRuleSet(sheet) {
var result = {
selectors: [],
rules: []
};
for(var i = 0, l = sheet.rules.length; i < l; i++) {
var rule = sheet.rules[i];
if (rule.styleSheet && rule.href /* instanceof CSSImportRule*/) {
checkCSSRuleSet(rule.styleSheet);
} else if (rule.selectorText /* instanceof CSSStyleRule*/) {
var hoverSelectors = getHoverSelectors(rule);
if (hoverSelectors.length > 0) {
if (checkStyles(rule)) {
Array.prototype.push.apply(result.selectors,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment