Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ID of clicked element with jQuery

I have the following html:

<a href="#" id="#1" class="pagerlink" >link</a>
<a href="#" id="#3" class="pagerlink" >link</a>
<a href="#" id="#2" class="pagerlink" >link</a>
/*etc.... */

and the following jQuery script:

$(document).ready(function() {

    var $container = $('.gallery_r').cycle({ 
        fx:     'scrollHorz', 
        speed:   500, 
        timeout: 0 
    }); 

    $('a.pagerlink').click(function() { 
        var id = $(this).attr('id');
        $container.cycle(id); 
        return false; 
    }); 

});

the 'pagerlink' links control are to jQuery Cycle slideshow. If I swap this line:

$container.cycle(id); 

for this

$container.cycle(7); 

it works... (obviously only navigating to slide number 7). So, my question is how can I pick up the ID of the link being clicked and pass it into that line?

Thanks in advance!

like image 508
Adam Avatar asked Oct 20 '11 15:10

Adam


People also ask

How do I get the clicked element id?

We can get the ID of the element that's clicked from the click event handler. We can either get the value from this if we use a regular function. Or we can get the same value from the event object of the click event handler.

How can I store ID of button clicked in jQuery?

click(function() { var clickedId= $(this). attr("id"); alert(clickedId); });

How do you target an element ID in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.


3 Answers

Your IDs are #1, and cycle just wants a number passed to it. You need to remove the # before calling cycle.

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('#', '')); 
    return false; 
});

Also, IDs shouldn't contain the # character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1.

<a href="#" id="pager_1" class="pagerlink" >link</a>

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('pager_', '')); 
    return false; 
});
like image 120
Rocket Hazmat Avatar answered Oct 23 '22 19:10

Rocket Hazmat


You just need to remove the hash from the beginning:

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id').substring(1);
    $container.cycle(id); 
    return false; 
}); 
like image 8
Richard Dalton Avatar answered Oct 23 '22 18:10

Richard Dalton


@Adam Just add a function using onClick="getId()"

function getId(){console.log(this.event.target.id)}
like image 5
Anurag M. Avatar answered Oct 23 '22 20:10

Anurag M.