How to get ID of clicked element with jQuery
Asked Answered
S

5

61

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?

Spalla answered 20/10, 2011 at 15:22 Comment(1)
# isn't a valid character in an [id].Exequatur
P
105

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; 
});
Plainsong answered 20/10, 2011 at 15:25 Comment(1)
Numeric IDs are actually allowed in HTML5.Justifier
E
9

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; 
}); 
Elyssa answered 20/10, 2011 at 15:24 Comment(1)
The official spec says that IDs should always begin with an upper- or lower-case letter, never a number (or a hash sign). Many browsers will allow it, but you can't expect them to.Wheelhorse
A
6

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

function getId(){console.log(this.event.target.id)}
Archegonium answered 6/12, 2019 at 10:17 Comment(0)
R
4

Your id will be passed through as #1, #2 etc. However, # is not valid as an ID (CSS selectors prefix IDs with #).

Rich answered 20/10, 2011 at 15:24 Comment(0)
Q
2

First off you can't have just a number for your id unless you are using the HTML5 DOCTYPE. Secondly, you need to either remove the # in each id or replace it with this:

$container.cycle(id.replace('#','')); 
Quartermaster answered 20/10, 2011 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.