# Toggling class on mouse hover

I am using this code to add a class on mouse hover to a link button and remove it on mouse leave.

jQuery(".banner-wrap__color-1 > .banner-wrap__inner > .banner-wrap__desc > .banner-btn > .btn-link").hover(function () {
jQuery(".banner-wrap__color-1 > .banner-wrap__inner").toggleClass("active");
jQuery(".banner-wrap__color-1").toggleClass("active");
});

jQuery(".banner-wrap__color-2 > .banner-wrap__inner > .banner-wrap__desc > .banner-btn > .btn-link").hover(function () {
jQuery(".banner-wrap__color-2").toggleClass("active");
});

jQuery(".banner-wrap__color-3 > .banner-wrap__inner > .banner-wrap__desc > .banner-btn > .btn-link").hover(function () {
jQuery(".banner-wrap__color-3").toggleClass("active");
});

jQuery(".btn-align > .btn-inverse").hover(function () {
jQuery(".service-box__style-1").toggleClass("active");
});

• Are you sure you don't just need some CSS hover rules? – Shaun H Jul 30 '15 at 13:36
• We could give you better advice if you also included your HTML so that we can understand what you are really trying to accomplish. (The generated HTML will do; we probably don't need to see the WordPress code that produces the HTML.) – 200_success Jul 31 '15 at 4:08

You could store in a variable so that the Dom doesn't need to be traversed several times:

var myvar = jQuery(".banner-wrap__color-1 > .banner-wrap__inner > .banner-wrap__desc > .banner-btn > .btn-link");


Then just use myvar instead of retrieving it again... A

• He doesn't query the same object more than once. The top level object is numbered 1,2, and 3 – Shaun H Jul 30 '15 at 15:14
• couldn't he get the parent node, then get the children when needed? – codys-hole Jul 30 '15 at 15:20
• I think the hover function should be assigned to .btn-link then let the parents be grabbed as needed. ...but .banner-wrap__color-1 is an oddball and has more being done. And I kinda want to see the html behind this, for a better assessment. – Shaun H Jul 30 '15 at 16:01
• jsfiddle.net/yrralej/qgLxa16r/1 please refer to this link for my complete code. ThankYou! – yrralej Aug 5 '15 at 6:30

Is hard to evaluate jquery without the DOM when you are making selectors.

You are using a lot of > check if you can use .find.

In a initial, state, theres a few lines repeated. that can be extracted in a outside function.

function toggleClass($container) {$container.find(".banner-wrap__desc > .banner-btn > .btn-link").hover(function () {
\$container.toggleClass("active");
})
}

toggleClass(jQuery(".banner-wrap__color-1"));
toggleClass(jQuery(".banner-wrap__color-2"));
toggleClass(jQuery(".banner-wrap__color-3"));


And the full code: http://jsfiddle.net/ja5py40o/

• I have try this code and its working! Thank you for the help! – yrralej Aug 5 '15 at 6:15