I'm trying to pass a changing variable to jquery function below but missing a piece.
$(document).ready(function(){
var area = "NW";
$("#NWbutton").click(function (){
$('#mainmap > img').attr('src', "some_web_"+area+"_address_forpics_time.gif");
});
});
For the "NWbutton" I need var area = "NW". I have 20 or so buttons with corresponding variables. How do I pass these for each button instead of writing out each variable?
2 Answers 2
data attributes provide the perfect solution to this problem. You can put whatever data is related to that button into the attribute, which you can then read in the click handler. Something like this:
<div id="mainmap">
<img src="foo.jpg" data-area="NW" />
<img src="bar.png" data-area="SW" />
</div>
$("#NWbutton").click(function (){
$('#mainmap > img').attr('src', function() {
return "some_web_" + $(this).data('area') + "_address_forpics_time.gif";
});
});
Comments
Following Rory McCrossan , individual button's or input[type=button]'s could includetext or value corresponding to selection variable for that element, i.e.g.,
<button>NW</button>
or
<input type="button" value="NW" />
html
<div id="mainmap">
<img src="foo.jpg" alt="NW"/>
<img src="bar.png" alt="SW"/>
<img src="baz.jpg" alt="NE"/>
<img src="foobar.png" alt="SE"/>
</div>
js
$(document).ready(function() {
// with `input` elements , substitute
// `input[type='button']` , `$(e.target).val()`
// for `button` , `$(e.target).text()` , respectively
$("button").click(function (e) {
var area = $(e.target).text();
$('#mainmap > img[alt='+ area +']')
.attr('src', "some_web_"
+ area
+ "_address_forpics_time.gif");
// console.log($("img[alt='" + area + "']").attr("src"))
});
});
#NWbuttonor.NWbuttonorbutton? what is justNWbutton?