Reputation: 532
I am trying to hover over an element, check if the class contains a prefix and if so, apply some style to this element. The problem with this, is that if I have a div with a class called "bluescript-contact-form", (notice the prefix "bluescript-") then this does not fire when I am hovering over a child element of this div. How can this be accomplished?
This is the code I have written so far:
var controls = {
clickedElement: "",
prefixCheck: function(c){
// classPrefix = "bluescript-"
return (c.indexOf(classPrefix) !== -1) ? true : false;
},
bindUIActions: (function(){
$(outputElement).on("load", function(){
$(outputElement).contents().find("*").on("click", function(e){
e.stopImmediatePropagation();
});
$(outputElement).contents().find("*").mouseenter(function(e){
e.stopImmediatePropagation();
if(typeof $(this).attr("class") !== "undefined"){
/* This works, but only on the current element.
It does not check if a parent contains a class,
that contains a prefix that matches. */
if(controls.prefixCheck($(this).attr("class"))){
$(this).css({
outline: onHoverBorder,
cursor: "pointer"
});
}
/* Else if( a parent contains a class that matches,
apply style to THIS parent element ) */
}
});
$(outputElement).contents().find("*").mouseleave(function(e){
$(this).css({
outline: "none",
cursor: "default"
});
});
});
})()
}
I hope this is clear enough. Any help would be appreciated. Thank you!
Upvotes: 1
Views: 404
Reputation:
stopImmediatePropagation stops the event from propagating up the DOM tree (It does not reach the parent). If for some reason you need to call that method, you can get the class of the parent node as $(this).parent().attr("class") . This code should work fine:
else if(controls.prefixCheck($(this).parent().attr("class"))){
// Your code here
}
If you need to change the style of all ancestors whose classes starts with a prefix, you should use the parents() method, see:
else{
$(this).parents().each(function(index,value){
if(controls.prefixCheck($(this).attr("class"))){
$(this).css({
outline: "none",
cursor: "default"
});
}
// Uncomment the next line if you only want to change the first match found.
// return false ;
});
}
You should use startsWith to check the prefix of the class:
prefixCheck: function(c){
// classPrefix = "bluescript-"
return c.startsWith(classPrefix);
},
or use indexOf correctly:
prefixCheck: function(c){
// classPrefix = "bluescript-"
return c.indexOf(classPrefix) === 0;
},
Otherwise you may get false positives.
Upvotes: 2