1

I have 5 images with the same function in a javascript field and I want to know how to be able to use the function once per image

my current code

function move()
{
    // move to the first now
    document.getElementsByTagName('div')[0].insertBefore
    (this, document.getElementsByTagName('div')[0].firstChild)
}

img1.onclick=move
img2.onclick=move
img3.onclick=move
img4.onclick=move
img5.onclick=move
BhandariS
  • 606
  • 8
  • 20
Aeroy
  • 25
  • 3
  • `img1.addEventListener("click", functionName)` and in function, do this at the end `this.removeEventListener('click', functionName)` – Rajesh Apr 03 '17 at 04:56
  • Wrap all the image in single `Div` and use `event bubbling` property based on target element . – ricky Apr 03 '17 at 04:56
  • Possible duplicate of [force javascript EventListener to execute once?](http://stackoverflow.com/questions/4878805/force-javascript-eventlistener-to-execute-once) – Rajesh Apr 03 '17 at 04:57
  • @ricky OP wants to run function **only once** in life cycle. Your solution will not help – Rajesh Apr 03 '17 at 04:58
  • *use the function once per image*. This statement is confusing. Also if thats the case, OP's code should work a bit as he is assigning `img.onclick`. May be the logic of function is incorrect and would get solved using `addEventListener`, but I guess we should wait until OP confirms. – Rajesh Apr 03 '17 at 05:04
  • @Rajesh - Sorry, I deleted my comment before I saw your reply, because I found that [the code shown works](https://jsfiddle.net/xpg3g1bv/) for the way I had interpreted the question (at least, it works in Chrome). So then I figured your interpretation must be correct. – nnnnnn Apr 03 '17 at 05:19
  • @Rajesh thanks i combined the addEventListner function with the {once:true} parameber after and i got it working – Aeroy Apr 03 '17 at 05:23
  • @Aeroy Glad I was able to help you. Also, do check the mentioned link as it discusses many other options as well. – Rajesh Apr 03 '17 at 05:26

2 Answers2

2

Set once to true at .addEventListener() third parameter

[img1, img2, img3, img4, img5]
.forEach(function(img) {
  img.addEventListener("click", move, {once:true})
});

var [img1, img2, img3, img4, img5] = document.images;

function move() {
  alert(this.alt)
}

[img1, img2, img3, img4, img5]
.forEach(function(img) {
  img.addEventListener("click", move, {once:true})
});
<img alt="1"><img alt="2"><img alt="3"><img alt="4"><img alt="5">
guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    Wow, I didn't realise `.addEventListener()` accepted options like that, so I looked it up: it should be pointed out that it isn't supported in IE *or* Edge. – nnnnnn Apr 03 '17 at 05:23
  • I didn't know about this property. +1. Also would like to request you to put a sample of this method on mentioned dupe as that is a long running thread and would get more exposure. :-) – Rajesh Apr 03 '17 at 05:23
  • @nnnnnn Have not used ie in some time, have not tried edge – guest271314 Apr 03 '17 at 05:24
  • I'm just going on what the MDN page said about compatibility. I assume Edge will get updated to support it sooner or later. – nnnnnn Apr 03 '17 at 05:26
  • @Rajesh The Question which you linked to http://stackoverflow.com/questions/4878805/force-javascript-eventlistener-to-execute-once is closed, yes? – guest271314 Apr 03 '17 at 05:26
  • @nnnnnn Have not used *indows, ie in some time; not sure. If necessary have used browserstack to check compatibility for an application at ie; chromium and firefox are FOSS browsers. – guest271314 Apr 03 '17 at 05:27
  • My apologies. Did notice it. – Rajesh Apr 03 '17 at 05:27
  • @Rajesh No worries. The current Question poses the relevant inquiry, yes? – guest271314 Apr 03 '17 at 05:30
  • @nnnnnn See https://fossbytes.com/difference-google-chrome-vs-chromium-browser/, https://www.slideshare.net/gauthamrajelango/introduction-about-foss-and-mozilla – guest271314 Apr 03 '17 at 05:42
  • Sorry, comment deleted before you replied because I thought I was getting off-topic. But anyway, if I were running a business I would not ignore MS browsers, because I couldn't afford to miss out on that big a percentage of potential customers. – nnnnnn Apr 03 '17 at 05:48
  • @nnnnnn If your content is attractive to users, and only served properly using chromium or firefox, the user will find a way to get, install and use chromium or firefox; over time decreasing the presumed reliance on a population using a proprietary browser where the source code is not FOSS. – guest271314 Apr 03 '17 at 05:49
  • @nnnnnn If popular "social media" sites announced their (user) content would be best viewed at chromium or firefox, what would be the percentage increase in chromium, firefox downloads over night? – guest271314 Apr 03 '17 at 05:56
  • At my workplace (and many others), the desktop environment is locked down and MS is the only choice. When shopping online, if the thing I want to buy is available from several websites but some of those websites don't work with my existing browser, I will buy the item from one of the sites that works without me needing to install anything. If a super popular site like the one you mentioned announced something like that there probably would be an increase in downloads, except for people like my parents who don't understand what any of that means. Or for people who use the phone app anyway. – nnnnnn Apr 03 '17 at 05:57
  • @nnnnnn Well, that is monopoly, of and in a work environment. Not so far reached of an estimation, as there was litigation as to the intent to monopolize the browser market by shipping the browser with the os, some time ago; for monopoly capital. If that was this users' work environment, that would have to be adjusted; that is, there is no benefit to using proprietary software within a work setting. The point being, there is always a choice. Many not so easy in the least, though sound in scope. It is left to the individual whether to follow and be beholden to monopoly capital, or not. – guest271314 Apr 03 '17 at 06:00
0

If the environment supports the 3rd parameter in addEventLister, that could is definitely better to use. However, if you need to work with legacy code (because you're working in an intranet, and/or you can't add a build step), you can have something like that:

var imgs = [img1, img2, img3, img4, img5];

for (var img, i = 0; img = imgs[i++];) {
  img.onclick = function() { move.call(this); this.onclick = null; }
}

This will works mostly everywhere, even where addEventListener is not supported at all. But I wouldn't recommend this if you have the proper support of addEventListener and at least ES6; I just add this answer for the record. If you have at least addEventListener (older IE doesn't, they've attachEvent) you could at least have:

var imgs = [img1, img2, img3, img4, img5];

for (var img, i = 0; img = imgs[i++];) {
  img.addEventListener("click", function listener() {
    this.removeEventListener("click", listener, false);
    move.call(this);
  }, false); // in some browser the `useCapture` is still not optional
}

If forEach is supported, the loop can be replaced with that.

ZER0
  • 24,846
  • 5
  • 51
  • 54