Jitender
Jitender

Reputation: 7971

Condition on event type in jquery

can we set condition on event type like if event is click then alert 'clicked' if event if mouseover then alert 'over'. but my function is alerting value when function is loading on the page

<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>

<script type="text/javascript">
$(function() {

    if($('.wait').click()) {
        alert('click')
    }
    else if ($('.wait').mouseenter()) {
        alert('mouseenter')
    }
})
</script>

<style>
    .wait {color:#F00}
    .nowait {color:#00F}
</head>

<body>
    <div class="wait">abc.....</div>
    <div class="wait">abc.....</div>
    <div class="wait">abc.....</div>

</body>

Upvotes: 0

Views: 298

Answers (6)

Anthony Grist
Anthony Grist

Reputation: 38345

If you're binding multiple event handlers to the same objects, I would personally pass an event map (an object) to the .on() function, like so:

$('.wait').on({
    click: function(e) {
        alert('click');
        // handle click
    },
    mouseover: function(e) {
        alert('mouseover');
        // handle mouseover
    }
});

However, if all you wanted to do was output the event type, there's an easier way to do that:

$('.wait').on('click mouseover', function(e) {
    alert(e.type);
});

Upvotes: 0

fatiDev
fatiDev

Reputation: 5992

try this

(document).ready(function() {
   $('.wait').bind('click dblclick mousedown mouseenter mouseleave',
               function(e){
               alert('Current Event is: ' + e.type);
                    });
                   });

Upvotes: 2

Sushanth --
Sushanth --

Reputation: 55740

Write up separate events to handle them..

$('.wait').on('click',function(){
        alert('Click Event !!');
    });

   $('.wait').on('mouseenter'f,unction(){
        alert('MouseEnter Event !!')
    });

Upvotes: 0

Database_Query
Database_Query

Reputation: 634

try simply

   $('.wait').click(function(){
        alert('click')
    });

and

   $('.wait').mouseenter(function(){
        alert('mouseenter')
    }); 

Upvotes: 0

sp00m
sp00m

Reputation: 48817

Your syntax is wrong, use instead:

$(".wait")
.click(function(event) {
    alert("click");
    // do want you want with event (or without)
})
.mouseenter(function(event) {
    alert("mouseenter");
    // do want you want with event (or without)
});

Upvotes: 3

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

The idea in this case is to define different handlers to different event types :

   $('.wait').click(function(){
        alert('click')
    });
   $('.wait').mouseenter(function(){
        alert('mouseenter')
    });

Upvotes: 3

Related Questions