1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

jQuery - Clicks

Discussion in 'jQuery' started by cancer10, Jan 28, 2009.

  1. #1
    Hi

    I have 3 different images on my page, with same IDs for each. And names for each images as img1, img2, img3 respectively

    I am using the following function in jQuery, but for some reason, the alert prompts me with the first image name no matter which image i click.


    
    $(document).ready(function(){
    				   	$("#img_skin").click(function(){
    												  
    							
    																							alert($("#img_skin").attr("name"));
    																						 });
    
    Code (markup):
    Plz help

    Thanx
     
    cancer10, Jan 28, 2009 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    er. you can't have more than 1 element with the same id on the page

    <img id="img_skin" ... />
    <img id="img_skin" ... />
    <img id="img_skin" ... />

    the dom will reference the first one. that's it.

    i suggest you do:
    
    <img src="blah1.jpg" class="img_skin" data-id="1" name="hi 1" />
    <img src="blah2.jpg" class="img_skin" data-id="2" name="hi 2" />
    <img src="blah3.jpg" class="img_skin" data-id="3" name="hi 3" />
    
    // class based selector, check to see it is not $$ - else, probably getElements()
    $("img.img_skin").each(function(im) {
        im.click(function() {
            alert(im.attr("data-id"), im.attr("name")); // will alert 1, 2 or 3. or name...
        });
    });
    PHP:
    p.s. not 100% on the jquery syntax but it ought to work same as the mootools one, cant be arsed to check it.

    good luck
     
    dimitar christoff, Jan 29, 2009 IP
  3. cancer10

    cancer10 Guest

    Messages:
    364
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Solved.

    Thanx for the help :)
     
    cancer10, Jan 29, 2009 IP
  4. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thought I'd post here since I've been using jQuery for awhile and like to help people out with it. While it's not proper XHTML to use the same ID on multiple elements, you can still do it; you just weren't referencing it properly. When you're binding a function to something like click(), you can reference the actual element they clicked with 'this'!

    $(document).ready(function(){
        $("#img_skin").click(function(){
            alert($(this).attr("name"));
        });
    });
    Code (markup):
    However, since I said that it's not proper to use same ID on multiple elements, I'm going to suggest as dimitar christoff did and say to give them all the same class name instead. But I don't recommend his code as it's way more than you need (though he did admit to not being 100% with how jQuery works). Just use the same code as above but changing it to reference the class instead of the ID.

    $(document).ready(function(){
        $(".img_skin").click(function(){
            alert($(this).attr("name"));
        });
    });
    Code (markup):
    That's it!
     
    zerxer, Jan 31, 2009 IP
  5. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #5
    sure you can - and you shouldn't need to apply a selector to it - so no $(this), just this.attr as this contains the object already. i purposefully avoid using examples with 'this' here as things stop working so nicely once a few anonymous functions stack up and people don't know how to bind (no assumptions, sorry).
     
    dimitar christoff, Jan 31, 2009 IP
  6. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #6
    No, "this" contains the HTML DOM object, not the jQuery object, so you still have to wrap it with the jQuery object selector in order to use jQuery functions with it (.attr()). And using "this" in jQuery's bind functions is perfectly fine and is recommended.

    Here's a working version of yours though (some slight problems originally):
    
    <script type="text/javascript">
            $(function(){
                $("img.img_skin").each(function(i, im) {
                    $(im).click(function() {
                        alert($(im).attr("data-id"), $(im).attr("name")); // will alert 1, 2 or 3. or name...
                    });
                });
            });
    </script>
    Code (markup):
     
    zerxer, Jan 31, 2009 IP
    dimitar christoff likes this.
  7. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #7
    this is rather funny. so there is a distinction between a jquery object and a dom object? lol. of course, it just downed on me - '$' is not a simple selector like in mootools, it is actually the jquery namespace!

    forgive me for saying that this seems rather wasteful - it makes perfect sense now as .click is only a method of jquery - whereas in mootools, it extends native constructs like objects etc. instead.

    does that mean that $(expression) is always parsed through the selectors engine or does it make a distinction based upon the type of argument it gets? i'd hate to think it looks through dom each time you do $(object)...

    also, the "each" arguments error - in mootools, they are reversed as function (iteration, counter) which makes far more sense--you don't always need to know the count but you can if you want to, whereas in jquery it seems you have no choice.

    thanks for this once again, rep inbound--but you have also reiterated in a very practical way for me why I should stick to my framework and steer clear of jquery--and i shall continue to do so in the future.

    for reference, here is the above in mootools proper:

    window.addEvent("domready", function() {
        $$("img.img_skin").addEvent("click", function() { // no need for each, it will determine the argument is an array and apply to all...
            console.log(this.get("data-id"), this.get("name"));
        });
    });
    PHP:
    another thing i should apologise for is that alert is not like console.log and it does not accept multiple arguments...
     
    dimitar christoff, Jan 31, 2009 IP
  8. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Wait, what? You're talking about .click() not being a native construct to the actual DOM object when in your mootools example you had to wrap "img.img_skin" with $$() just to use the addEvent() method? I don't get what the difference here is.

    And no, I don't think if you do $(this), that it has to search through the DOM for it.. wouldn't have to search anyways considering "this" is already the DOM object, why would it then have to search for that DOM object?

    I'd say mootools is the same except that with your function bindings, when it passes "this" to the function, it already has the $$() wrapper around it. I could do var x = $("img") and then x.jQuery_function() too instead of having to do $(x) to call the function.


    Oh and "// no need for each, it will determine the argument is an array and apply to all...", you don't need 'each' for jQuery either. Doing $(selector).click() would obviously bind the function to the click event for all matched elements too. I don't really see any huge differences yet between mootools and jQuery or, for that matter, any reasons why jQuery would be a lot worse.

    I guess. I never use those anyways. Who needs the iteration when it's already passed as 'this'? Really don't need either of the function's possible parameters. The only time they're useful is when you're looping through a JSON object so the 'i' and 'val' parameters passed (respectively) would be the current index name and value, just like a PHP foreach() loop ($i=>$val).
     
    zerxer, Jan 31, 2009 IP
  9. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #9
    erm not so. i bind it to the selector function, yes, but this is just for convenience. consider this:

    a basic page with some elements and either framework. go outside the framework and reference a dom element. for example:
    var foo = document.getElementById("foo");
    // now, apply a click event to foo in both frameworks:
    
    // mootools:
    foo.addEvent("click", function() {}); // the native element is extended to support addEvent, amongst other things.
    
    // jquery:
    $(foo).click(function() { }); // we go through the jquery name space and just reference the object
    
    // won't work in jquery:
    foo.click();
    
    // element is extended in mootools so you can use methods like:
    foo.addClass("bar").addEvents({
        click: function() {
        },
        mouseebter: function() {
    
        } // ... more events.
    }).fade(0,1).removeClass("foo").set({
        html: "<h1>hello</h1>",
        styles: {
            padding: 2,
            float: "left",
            left: foo.getParent().getPosition().x - 20
        }
    });
    
    PHP:
    i hope this makes it clear what a substantial difference in approach we have despite of the similar syntax--this is what i meant by the revelation about $ not being a selector in jquery :D

    as for each loop referencing 'this', fair enough although but i can see how sometimes you may want to bind the parent function's 'this' instead to keep the scope or whatever... so it may come handy
     
    dimitar christoff, Feb 1, 2009 IP