Tuesday, 15 September 2015

Javascript: function with "this" undefined -



Javascript: function with "this" undefined -

i'm new javascript , attempting write function changes color of text, "this" keeps returning undefine, , not changing text color. here's code, appreciate help.

<h1> <ul><div class="info" id="info" onclick="this.style.color= '#9dc8ba'">info </div></ul> <ul><div class="menu" id="menu" onclick="test1()"<!--this problem is-->menu</div></ul>

here's javascript

function test1() { this.style.color= '#9dc8ba'; }

you have pass reference of dom element function

<div class="menu" id="menu" onclick="test1(this)">/div>

in above html, refers current dom element div of id menu.

and refer , modify dom within function

function test1(obj) { obj.style.color= '#9dc8ba'; }

side note: seem having same name class , id div, not practice. remember class corresponds grouping of elements , id corresponds unique elements.

javascript

No comments:

Post a Comment