Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .click() not binding properly

Tags:

jquery

I want to perform some action when a link is clicked, I am using the following code to achieve this however it rarely works. If I click the link it usually refreshes the page, and 1/10 times it'll actually pop up "Hi". What is wrong?

$(document).ready(function()
{
    $('#slconfiglink').click(function()
    {
        alert("hi");
        return false;
    });

});

HTML:

<ul>
    <li><a href="#" id="slconfiglink">Config 1</a></li>
</ul>

Note that the ID's are not replicated elsewhere in the HTML

like image 395
Chris Avatar asked May 12 '10 13:05

Chris


2 Answers

Make sure to give your <a> a valid href, like this:

<a href="#" id="slconfiglink">Config 1</a>

Your anchor needs to have an href or a name to be valid, otherwise you'll get some funny behavior that'll vary by the browser used.

Also, unless you need the anchor for hover CSS, etc...you have the option to put the click handler right on the <li>, like this:

<ul>
  <li id="slconfiglink">Config 1</li>
</ul>

A few other things to check, make sure that ID is unique, if it's not use a class, like class="slconfiglink" and your selector would be ".slconfiglink" instead of "#slconfiglink".

If your elements are being added on the fly, change from

$('#slconfiglink').click(function() {

To use .live() like this (or with the class selector, if the multiple comment applies):

$('#slconfiglink').live('click', function() {
like image 55
Nick Craver Avatar answered Oct 16 '22 20:10

Nick Craver


Is the element being created dynamically? If you are adding it using Javascript, you'll need to reattach your event handler after it's been added to the DOM.

like image 28
David Yell Avatar answered Oct 16 '22 18:10

David Yell