Wednesday, 15 February 2012

javascript - Clicking on a link to display images -



javascript - Clicking on a link to display images -

i'm new programming , working on website displays list of links. clicking on specific link, displays images. i'm wondering if need add together event listener each link because if have 100 links, mean i'll have write 100 event listeners?

document.getelementbyid("monkwhosold").addeventlistener("click",function() {disp_img(/monkwhosold)});

the above event listener example, user clicks 1 of links , disp_img function called img folder path passed parameter.

there many ways solve this. here's one.

<a href="#" class="image-link" data-url="/monkwhosold"> <a href="#" class="image-link" data-url="/anotherimage"> ...

then in javascript can write:

// find <a> tags class of 'image-link' var links = document.queryselectorall('a.image-link'); // loop through them (var = 0; < links.length; i++) { var link = links[i]; // hear click event link.addeventlistener('click', function() { // on click, show image using url data-url attribute disp_img(link.data.url); }); }

this doesn't utilize jquery. if you're starting out programming these days, think it's worth learning dom stuff directly. 1 time upon time wasn't easy or didn't work across browsers, , jquery valuable. that's less true nowadays, though still can quite convenient.

in code there 3 functions need learn:

queryselectorall find elements match css selector addeventlistener attach callback function particular event element.data access info stored in data-foo="bar" attributes of html

other it's for, function , other simple elements of language.

javascript html

No comments:

Post a Comment