I have the following:

Javascript:
$(".bg .thumb_wrapper").click(function() {
$(".bg .thumb_wrapper").removeClass("active");
$(this).addClass("active");
});
So every time I click on a new background, it is highlighted and is given a class “active” and the previous active class is removed.
Now all I need to do is create a variable and set it to the data-name attribute for that active item.
Here is the HTML:
<div class="thumb_wrapper active">
<img src="images/backgrounds/thumb/bg2.jpg" data-name="bg2.jpg">
</div>
So if I put it in the click function, it will work fine:
var bg = $(".bg .thumb_wrapper.active img").attr("data-name");
console.log(bg);
so every time it is clicked, it tells me the value. But I need to access that variable outside of that function.. so it needs to be global.
Is there anything I can do to grab the value of data-name on the start of the page, not on a click function? And when I do click a new BG and the active class is updated, then the variable will be updated also?
Hope that makes sense.
Thanks!
Declare the variable outside the function so its scope is not limited to the click handler.
If you want the value of
bgto be updated everytime a new BG is clicked, you must do the assignment in the click handler as above.Live Example