Created
December 28, 2020 18:47
-
-
Save macu/ec5ebac83d673c711dfbb073108fd9a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.fn.isBefore = function(e2) { | |
// var all = $(context || document).find("*"); | |
// return all.index(this[0]) < all.index($(sel)); | |
let e1 = $(this).get(0); | |
e2 = $(e2).get(0); | |
let p1 = $(e1).parents(); // returns a jQuery object | |
let p2 = $(e2).parents(); // ordrered from the immediate parent up | |
for (var i1 = 0; i1 < p1.length; i1++) { | |
let i2 = p2.index(p1[i1]); | |
if (i2 >= 0) { | |
let commonParent = p1[i1]; | |
// take e as common sibling if common parent is index 0 | |
let common1 = i1 > 0 ? p1[i1 - 1] : e1; | |
let common2 = i2 > 0 ? p2[i2 - 1] : e2; | |
if (common2 === e1) { | |
return true; // parent before child | |
} | |
let $commonSiblings = $(commonParent).find('>*'); | |
return $commonSiblings.index(common1) < $commonSiblings.index(common2); | |
} | |
} | |
return false; | |
}; | |
// Example | |
// $('#something').isBefore('#somethingElse') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment