Chris
Chris

Reputation: 27384

jQuery .click() not binding properly

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

Upvotes: 5

Views: 6010

Answers (5)

Sundararajan S
Sundararajan S

Reputation: 1378

could you try changing the href of anchor tag to 'javascript:void(0);'

Upvotes: 0

Jayme Tosi Neto
Jayme Tosi Neto

Reputation: 1239

I had the same problem yesterday.
To solve I've just used simple javascript in combination with jQuery.

That's what I've done:

<script>
    function yourFunction()
    {
        alert("hi");
        //$("#slconfiglink").doWhatYouWant();
    }
    $(document).ready(function()
    {
        $("#slconfiglink").attr('onclick', 'yourFunction();')
           //I did it in this way to garantee the function 
           //will only be called after the DOM is ready
    });
</script>

<a id="slconfiglink" href="javascript:;">click me</a>

I hope this could be useful! ^^

Upvotes: 0

Fabian
Fabian

Reputation: 13691

Use the preventDefault() method to make sure the browser doesnt follow the link.

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

Upvotes: 2

David Yell
David Yell

Reputation: 11855

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.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630409

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() {

Upvotes: 5

Related Questions