janicehoplin
janicehoplin

Reputation: 397

Why isn't my javascript onclick event triggered on the first click?

I have a div element that I click and it is supposed to trigger a check of the current innerHTML value of the element and then match to a condition and make changes.

Is it the position of the script relative to the position of the element or is it about loading? The script is above the element but it works on the second and subsequent clicks(alternating not shown).

The innerHTML won't change on first click but another event like hiding something works on first click.

HTML

<div id="element" onclick="changeHim();">Change me upon click.</div>

Script

function changeHim() {
var currentLabel = document.getElementById("element");
if(currentLabel=="Change me upon click"){
document.getElementById("element").innerHTML="You have been changed.";
}

}

Upvotes: 0

Views: 95

Answers (5)

SPiCaRia
SPiCaRia

Reputation: 121

The result of getElementById is a DOM element instead of the content of that div.
So the statement

if (currentLabel == "change me upon click")

is never true.

Upvotes: 2

the Explorer
the Explorer

Reputation: 103

Error No 1.

you should declare

var currentLabel = document.getElementById("element").innerHTML

instead of

var currentLabel = document.getElementById("element");

Error No 2.

Function closing Bracket } is missing

Error No 3.

Use

if(currentLabel=="Change me upon click."){

Instead of

if(currentLabel=="Change me upon click"){

because one DOT(.) is missing in the (innterHTML) text

the corrected FULL code (tested) is given below

<script>
  function changeHim() {
    var currentLabel = document.getElementById("element").innerHTML;
    if(currentLabel=="Change me upon click."){
      document.getElementById("element").innerHTML="You have been changed.";
      }
    }
</script>

<div id="element" onclick="changeHim();">Change me upon click.</div>

Upvotes: 2

ozil
ozil

Reputation: 7117

your if statement is causing the problem it should be if (currentLabel.innerHTML == "Change me upon click.")

function changeHim() {
    var currentLabel = document.getElementById("element");
    if (currentLabel.innerHTML == "Change me upon click.") {
        document.getElementById("element").innerHTML = "You have been changed.";
    }
}
<div id="element" onclick="changeHim();">Change me upon click.</div>

Upvotes: 1

Sajal
Sajal

Reputation: 4401

To fetch the text label as:

var currentLabel = document.getElementById("element").textContent;

or

var currentLabel = document.getElementById("element").innerHtml;

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You need to check with innerHTML:

if(currentLabel.innerHTML=="Change me upon click"){

Also, fix the missing closing brace } of your function.

Upvotes: 1

Related Questions