John Glabb
John Glabb

Reputation: 1621

onClick event for Div content

Here is my simple xPage:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
    <xp:div
        style="border-color:rgb(255,0,0);border-style:solid;border-width:thin"
        id="div1" styleClass="divStyleClass1">
        <xp:label value="Label" id="label1" styleClass="labelStyleClass">
        </xp:label>
        <xp:eventHandler event="onclick" submit="false">
            <xp:this.script><![CDATA[alert(thisEvent.target.className);
if(thisEvent.target.className=="divStyleClass1"){
    thisEvent.target.className="divStyleClass2";
} else {
    thisEvent.target.className="divStyleClass1";
}]]></xp:this.script>
        </xp:eventHandler>
    </xp:div>
</xp:view>

I want to change DIV styleClass by onClick event. And it works fine till I click on any element inside the DIV, e.g. on the label. Obviously thisEvent.target points to the label object and it fails.

So how to fix it so it changes DIV styleClass regardless of where and what you click inside?

Upvotes: 2

Views: 211

Answers (2)

Ouroborus
Ouroborus

Reputation: 16865

A possibility is to use the currentTarget property of the event rather than target. currentTarget contains the node the event handler is attached to.


If that's not sufficient, you might be able to do something like this:

var target = thisEvent.target;
while(target != null) {
  if(target.nodeName == "DIV") {
    break;
  }
  target = target.parentNode;
}

target will then contain the nearest ancestor node that is a div or null.

Upvotes: 5

Yaser
Yaser

Reputation: 5719

Instead of checking the target, check the element itself:

var div = document.getElementById("div1");
if(div.className == "divStyleClass1") {
    div.className = "divStyleClass2";
} else {
    div.className = "divStyleClass2";
}

Upvotes: 0

Related Questions