1

In my sample HTML code i got some buttons with a default function to change the text and style on onclick event:

<button onclick="changeText(this)">Hit Me!</button><br>
<button onclick="changeText(this)">Hit Me!</button><br>
<button onclick="changeText(this)">Hit Me!</button><br>
<button onclick="changeText(this)">Hit Me!</button><br>
<button onclick="changeText(this)">Hit Me!</button><br>

<script>
function changeText(id) {
    id.innerHTML = "Ouch!";
    id.style.color="red";
    id.onclick= again(this);
}

function again(id) {
    id.innerHTML = "Again!";
    id.style.color=#FF0000;
}
</script>

I'm trying to change the onclick event at the end of the default function:

id.onclick= again(this);

But it doesn't work;

This is the jsfiddle link

I've tried solutions in this question and this one

this:

 id.onclick = function(this) { id.innerHTML = "Again!"; id.style.color=#FF0000; }

and this:

 id.setAttribute( "onclick", "javascript: again(this);" );

but none of them works.

notice that I need this as the parameter to send into the function.

And I need a javascript solution not JQuery

What am I doing wrong?

Community
  • 1
  • 1
Ghasem
  • 14,455
  • 21
  • 138
  • 171

3 Answers3

0

Your code had some syntax errors, id.style.color=#FF0000;, the hex value should be a string. id.style.color="#FF0000";

And in this line:

id.onclick = again(this);

You're calling the again function & assigning the return value to id.onclick. If you want to assign a function just use id.onclick = again

Here's your code working, with some minor modifications.

function changeText(element) {
    element.innerHTML = "Ouch!";
    element.style.color="red";
    element.onclick = again; //Assign "again" function.
}

function again() {
    //this is the clicked element.
    this.innerHTML = "Again!";
    this.style.color="#FF0000";
}
 button {
  font-size:20px;
  color:#0C6C89;
}
<!DOCTYPE html>
<body>
<button onclick="changeText(this)">Hit Me!</button><br>
<button onclick="changeText(this)">Hit Me!</button><br>
<button onclick="changeText(this)">Hit Me!</button><br>
<button onclick="changeText(this)">Hit Me!</button><br>
<button onclick="changeText(this)">Hit Me!</button><br>
</body>
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
0

Try the following:

id.onclick= function onclick(event){again(this);}
Felipe
  • 1
-1

If you need lowcoupling you could do this:

function changeText(id) {
    id.innerHTML = "Ouch!";
    id.style.color= "red";
    // send the id
    id.onclick= again(id);
}

function again(id) {
    id.innerHTML = "Again!";
    id.style.color = "#FF0000";
}
dexhering
  • 422
  • 3
  • 13