Ryley Ameden Ryley Ameden - 14 days ago 5
jQuery Question

Combining / Refining two identical blocks of jQuery

I have two blocks of code that function exactly the same but need to fired independently in order to prevent overlap of functionality.



//Block One
jQuery('.top_searchicon').on('click touchstart', (function(e) {
e.preventDefault();
jQuery(this).toggleClass('active');
jQuery('.top_blog_search').toggleClass('active');
}));

//Block Two
jQuery('.searchicon').on('click touchstart', (function(e) {
e.preventDefault();
jQuery(this).toggleClass('active');
jQuery('.blog_search').toggleClass('active');
}));





Thank you very much.

Answer

You can combine selectors using a comma (,). You can then use is() and a ternary to choose the relevant element to set the active class on. Try this:

jQuery(function($) {
    $('.top_searchicon, .searchicon').on('click touchstart', (function(e) {
        e.preventDefault();
        var $el = $(this).toggleClass('active');
        var targetClass = $el.is('.searchicon') ? '.blog_search' : '.top_blog_search';
        $(targetClass).toggleClass('active');
    });
});

Note the use of the parameter in the ready handler, this enables you to still use the $ to reference jQuery within the scope of your document.ready handler.

Comments