nexuscreator
nexuscreator

Reputation: 845

JQuery anchor link selector issue

I'm trying to select the list anchor link using jquery. Though 'list' link doesn't exist in the page as shown in the console output, it seems 'click' is still getting triggered. What could be causing 'list' and 'add' to trigger? I have this simple code using jquery 1.10.2:

<!-- <a href="#list">List</a> -->
<a href="#delete">Delete</a>
<a href="#add">Add</a>

<script>
    jQuery(document).ready(function($) {
        if ($('a[href$="#list"]').length>0){
            console.log('list found');
        }else{
            console.log('list not found');
        }

        function opentab(value){
            console.log('opentab: ' + value );
            //perform task here            
        }

        $(document).on('click', 'a[href="#list"]', opentab('list'));
        $(document).on('click', 'a[href="#add"]', opentab('add'));
    });
</script>

console output:

list not found
opentab: list
opentab: add

Here's jsfiddle link: http://jsfiddle.net/2FHf6/

Upvotes: 2

Views: 72

Answers (3)

RGS
RGS

Reputation: 5211

 $(document).on('click', 'a[href="#list"]', function(e){ 
         opentab('list');
 });
 $(document).on('click', 'a[href="#add"]', function(e){
        opentab('add');
 });

Demo:

http://jsfiddle.net/XJhN6/

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

you need to declare a function in the event that when this event occurs call this function, currently the method inside event is called on page load as your way of calling is not right:

do like this:

$(document).on('click', 'a[href="#list"]', function(){
            opentab('list')
        });
        $(document).on('click', 'a[href="#add"]', function(){
            opentab('add')
        });

UPDATED FIDDLE

Upvotes: 2

Niklas
Niklas

Reputation: 1777

See this updated fiddle.

When you want to call a function on an event triggered and the function needs to pass values, you have to do it in an "wrapper" function, like this:

jQuery(document).ready(function($) {
    if ($('a[href$="#list"]').length>0){
        console.log('list found');
    }else{
        console.log('list not found');
    }

    function opentab(value){
        console.log('opentab: ' + value );
        //perform task here            
    }

    $(document).on('click', 'a[href="#list"]', function() {
        opentab('list');
    });
    $(document).on('click', 'a[href="#add"]', function() {
        opentab('add');
    });
});

Otherwise it will be called when the event listener is set, not on the actual event.

Upvotes: 1

Related Questions