Sikander Sikander - 5 years ago 194
HTML Question

Javascript: getting data-attr on click event

i am trying to alert

data-attr
value on click event like this

<div class="col-md-2 col-xs-2" onclick="changeImage(event)">
<img src="img/img1.jpg" data-attr="img1.jpg">
<img src="img/img2.jpg" data-attr="img2.jpg">
</div>

<script type="text/javascript">
function changeImage(event){
var target= event.target;
alert(target.data-attr);
}
</script>


here if i target src of image that will alert but
data-attr
wont how can i do this pleas help

Answer Source

You should use the dataset property to retrieve data-* attributes:

function changeImage(event) {
    var target = event.target;
    alert(target.dataset.attr);
}

Working example

Also, seeing as you tagged this question with jQuery, here's a jQuery implementation without the ugly onclick attribute:

<div class="col-md-2 col-xs-2">
    <img src="img/img1.jpg" data-attr="img1.jpg">
    <img src="img/img2.jpg" data-attr="img2.jpg">
</div>
$(function() {
    $('div.col-md-2').on('click', 'img', function() {
        alert($(this).data('attr'))
    });
});

Example fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download