Zabs
Zabs

Reputation: 14142

jQuery - trigger a custom event on a link

I am trying to run this custom 'getOffer()' event using jQuery

<a href="javascript: void getOffer();" title="Submit for offer"><img src="images/img.jpeg"></a>

I have tried the following but it doesn't seem to work (I am using the Firefox Firebug console.log window)

$('a[title="Submit for offer"]').trigger('getOffer');

This is the page I am trying this on: http://bit.ly/1dpIMFk Can anyone suggest any ideas?

Upvotes: 0

Views: 253

Answers (4)

Ashwani
Ashwani

Reputation: 3491

Trigger will not function because it search click attribute in element. Work around for this can be is:

Add click attribute to the element and then call the jquery function.

<a href="javascript: void getOffer();" title="Submit for offer"></a>
    <button value="yu" onclick="getOffer();"/>
<script>

 $("a[title='Submit for offer']").attr("onclick",$("a[title='Submit for offer']").attr('href')); // get value from href
 $("a[title='Submit for offer']").trigger('click');  


 function getOffer()
 {
     alert('j');
 }
</script>

Upvotes: 1

Roger Barreto
Roger Barreto

Reputation: 2284

Creating an custom event on jQuery

First add some identifier (id/class) to your link

<a id="linkOffer" title="Submit for offer"><img src="images/img.jpeg"></a>

Then, create your CUSTOM event.

//The function that will to the getOffer things
function getOffer() {
    //Do get offer...  
}

$(document).ready(function(){

    //Custom event pointing to the function
    $('a#linkOffer').on('getoffer',getOffer);

    //Default click event
    $('a#linkOffer').on('click',function(e){
         //Do click stuff.

         //Trigger your custom event.
         $(this).trigger('getoffer');

         //If you wish to not move the page, prevent the default link click behavior (moveing to other page)
         e.preventDefault();
    });
});

Upvotes: 1

Ozan Deniz
Ozan Deniz

Reputation: 1087

You can use

<a href="#" onClick="getOffer();"><img src="images/img.jpeg"></a>

Upvotes: 1

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

 <a href="javascript: void getOffer();" title="Submit for offer"><img src="images/img.jpeg"></a>

$(document).ready(function(){
  $('a[title="Submit for offer"]').trigger('getOffer');
});

function getOffer(){
alert('link clicked');
}

Seems working fine for me.I think you didnt wrapped your event trigger in document ready. DEMO

Upvotes: 1

Related Questions