Return image value

Asked

Viewed 67 times

0

I have this html code:

<label>
     <img class="jogo" value="lol" src="../cdn/img/jogos/lol.png">
     <img class="jogo" value="csgo" src="../cdn/img/jogos/csgo.png">
</label>
<br><div class="atual"> </div>

I wanted in the div below to show the value of the images above ( lol /csgo )

$(function(){
 $(".jogo").click(function(){

    $(".jogo").animate({opacity:0.5},{duration:100});
    $(this).animate({opacity:1},{duration:100});
    var jogo = $(this).val();
    $(".atual").html(jogo);
 });
});

I don’t know how I do it :/

Code jsfiddle: http://jsfiddle.net/xj1L52h3/

______________________________________________

Edited

I have another question, I wanted to make sure that when I clicked on 1 of the images a menu appeared and when I clicked on the other one, what was already there disappeared and another appeared.

http://jsfiddle.net/xj1L52h3/7/

2 answers

2


I don’t know exactly why it didn’t work but I suspect it’s because the tag img does not work with the attribute value. This attribute is used in form elements. So if you change the .val() for .attr("value") will solve.

Fiddle

But the correct in this case is to use the attributes data, example:

<img class="jogo" data-game="lol" src="../cdn/img/jogos/lol.png" />
<img class="jogo" data-game="csgo" src="../cdn/img/jogos/csgo.png" />

And then to access the attribute:

$(this).data("game")

Fiddle

On the effect of the images, I would like to suggest that you use this selector:

$(".jogo").not(this).animate({opacity:0.5},{duration:100});

Because then you don’t run this animation on all the images, only the ones that weren’t clicked.

Fiddle

  • It worked perfectly, I thought the same thing about the tag img not work with the value, but n knew how to solve. Thank you :)

  • I edited the topic there, you can help me?

  • @xdam98 http://jsfiddle.net/xj1L52h3/8/

  • Thanks, it all worked out.

2

You have to take the "src" attribute from the image with the . attr from jQuery, follow the code:

http://jsfiddle.net/bxcvahko/2/

$(function(){

    $(".jogo").click(function(){

        $(".jogo").animate({opacity:0.5},{duration:100});
        $(this).animate({opacity:1},{duration:100});
        var jogo = $(this).attr('src');

        jogo = jogo.slice(jogo.lastIndexOf('/') + 1, jogo.length);
        jogo = jogo.split('.')[0];

        $(".atual").html(jogo);
    });

});
  • @Dontvotemedown user did the same in a simpler way. However, thank you, that "split" will be useful to me in the future :D

  • 1

    A regex there would greatly improve this code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.