Reputation: 117
I read this thread and tried to use Ted Hopps method Function in javascript that can be called only once
But seems that i can't make it work properly. I want to create a div with JS by onclick="function()" on an image. But i want to do that just once.
function runOnce(f){
var executed = false;
return function () {
if (!executed) {
executed = true;
return f.apply(this,arguments);
}
};
}
function rollover() {
var new1=runOnce(myfunction);
new1(1);
}
function myfunction(){
var tr1 = document.createElement("tr1");
tr1.style.width = "50%";
tr1.style.height = "100%";
tr1.style.background = "red";
tr1.style.color = "white";
tr1.style.right= "0px"
tr1.style.top= "0px"
tr1.style.padding= "2%"
tr1.style.opacity= "0.6"
tr1.style.position = "fixed";
tr1.innerHTML = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
document.body.appendChild(tr1);
}
I call the rollover function from onclick
<img class="trans01button" onclick="rollover(1)" src="images/backgroundfragments_03.jpg" alt="Translation games" >
My problem is that it still executes the function multiple times. I made a jfiddle http://jsfiddle.net/RE3fp/ here but i can't make it work while my dreamweaver version works. I mean i can't make the "myfunction" div even to appear, while my problem is that it executes everytime i click the image.
Upvotes: 1
Views: 189
Reputation: 5212
You need move this line: var executed = false;
outside of runOnce
function scope.
Because always when you go inside runOnce
function you set yout flag to false.
Upvotes: 2