Deshwal
Deshwal

Reputation: 4162

Assign multiple functions to a same class/element using Jquery?

I have started learning Jquery today from W3Schools. I am trying some examples.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.mouseover').mouseover(function () {
                alert("Entered")
            })
        })
    </script>
<p class="mouseover">Enter and leave from here</p>
<p class="click">Click and double click here</p>
<p class="hover">Hover over here</p>

I want to assign two functions to the same class mouseover which takes two events mouseenter and mouseleave. I do not want to use hover. I just want to know the process how it can be done?

To assign different methods by selecting a same element. Like clicking on a class will do one thing, hovering over it will do other and so on.

Upvotes: 0

Views: 164

Answers (3)

giuseppe
giuseppe

Reputation: 105

Try the following, the problem you can have is that for clicking the item "mouseover" you have to hover it so it triggers the hovering function first... :

    $(document).ready(function () {
        $('.mouseover').mouseover(function () {
            alert("Entered")
        })
    });

        $('.mouseover').click(function () {
            alert("Clicked!")
        });
        
        $('.click').click(function () {
            alert("Clicked!")
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="mouseover">Enter and leave from here</p>
<p class="click">Click and double click here</p>
<p class="hover">Hover over here</p>

Upvotes: 0

dganenco
dganenco

Reputation: 1616

You should simply assign another event to your selector. Smth like this:

let $el = $('.mouseover');    

$el.on('mouseover', function() {
  console.log("Entered");
});

$el.on('mouseleave', function() {
  console.log("Leave");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="mouseover">Enter and leave from here</p>
<p class="click">Click and double click here</p>
<p class="hover">Hover over here</p>

Upvotes: 0

Udochukwu Enwerem
Udochukwu Enwerem

Reputation: 2843

No need to write separate functions. You can chain both on one object like this

$('.mouseover').on('mouseover', function() {
  console.log("Entered");
}).on('mouseleave', function() {
  console.log("Leave");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="mouseover">Enter and leave from here</p>
<p class="click">Click and double click here</p>
<p class="hover">Hover over here</p>

Upvotes: 1

Related Questions