contactmatt
contactmatt

Reputation: 18600

jQuery Click binding does not fire in IE8

The jQuery click binding is never fired in IE8 (works in IE9, Chrome, etc.) How can I get the click event to fire in IE8, and why is it not currently?

Note: I've tried changing the href to '#', but that is not working either.

$('<a/>', {
    id: 'anchor-id',
    href: 'javascript:void(0);',
    'class': 'button-next',
    html: 'HTML'
}).click(function() {
     alert('clicked');
}).appendTo($('#append'));​

version: 1.7.2

Upvotes: 2

Views: 10912

Answers (4)

oomlaut
oomlaut

Reputation: 773

Have you stopped event propagation?

Typically with links you have to do something like:

<a href="#">HTML</a>

This script would work:

jQuery('#someLink').bind('click', function(e){  
  e.preventDefault();  
  //.. do something  
});

NOTE: your javascript:void(); SHOULD have covered this, but just checking.

If it's not a "real" link, you're not forced to use the A element, as you can simulate hover events with the same jQuery that creates the object:

jQuery("<span>", {  
  text: "html",  
  id: "anchor-id",  
  "class": "button-next",  
  click: function() { /* do something */ },  
  mouseover: function() { /* hover over */ },  
  mouseout: function() { /* hover out */ }
}).appendTo(jQuery('#append')); 

Upvotes: 0

Jason Towne
Jason Towne

Reputation: 8050

Have you tried using .on()?

.on() will create an event handler for all current and future elements that match your selector. In the statement below the click event will be handled for all elements with a class of button-next regardless of when they are added to the DOM.

$(document).on('click', '.button-next', function(e) 
{ 
  //do something
});

Upvotes: 4

CodeLikeBeaker
CodeLikeBeaker

Reputation: 21312

I was able to get it to work in IE8 using the following:

<div id="append"></div>
<script>
    var aLink = $('<a/>', { id: 'anchor-id', href: '#',html : 'click me'}).on('click', function () {
         alert('clicked');
    });
    $('#append').append(aLink);


</script>

Also, make sure you do not have any console.log()'s in there. IE does not like them very much.

Upvotes: 0

Huangism
Huangism

Reputation: 16438

Try something like this

$(document).on('click', '.button-next', function() {
    // code here
});

Upvotes: 3

Related Questions