0

Is there a way to merge those scripts or make code more efficient? I'm new to jquery and I think I produce too much code. Is it possible to optimize it?

<script>
    jQuery(".myClass1").hover(
        function () {
            jQuery(".myClass1 h3").addClass("addedClass1");
        },
        function () {
            jQuery(".myClass1 h3").removeClass("addedClass1");
       }
    );
</script>


<script>
    jQuery(".myClass1").hover(
        function () {
            jQuery(".myClass1 h3").addClass("addedClass2");
        },
        function () {
            jQuery(".myClass1 h3").removeClass("addedClass2");
       }
    );
</script>

is it possible to optimize those also:

<script>
    jQuery(".myClass1").hover(
        function () {
            jQuery(".myClass1 h3").addClass("addedClass");
        },
        function () {
            jQuery(".myClass1 h3").removeClass("addedClass");
       }
    );
</script>


<script>
    jQuery(".myClass2").hover(
        function () {
            jQuery(".myClass2 h3").addClass("addedClass");
        },
        function () {
            jQuery(".myClass2 h3").removeClass("addedClass");
       }
    );
</script>

1 Answer 1

3

Try combining your selectors, taking advantage of the this object, and passing a single handler function employing the toggleClass method like so:

jQuery(".myClass1, .myClass2").hover(
    function () {
        jQuery(this).find("h3").toggleClass("addedClass");
   }
);

First, by combining your selectors ".myClass1, myClass2" with a comma between them, you can chain a single hover event to all elements of both classes.

Second, by using the handler function's this object, you are able to reference the current element that fired the hover event, without having to know its specific class.

Finally, by passing a single handler function and using the toggleClass method you perform the same action that two handler functions served with two separate calls to addClass and removeClass.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.