Jump to content

Add onclick to div


Bogey

Recommended Posts

html:

<div class='testClass' id='testID' onclick="addToList('<?php echo $ID_1;?>','<?php echo $ID_2;?>')"></div>

Javascript:

function addToList(newID,oldID){alert("ok_1");document.getElementById(newID).innerHTML=document.getElementById(oldID).innerHTML;document.getElementById(newID).className="newClass"; document.getElementById(newID).onclick = "removeFromList(newID)";document.getElementById(newID).onclick = removeFromList;document.getElementById(newID).onclick = "removeFromList('" + newID + "')";} function removeFromList(newID){alert ("ok_2");alert (newID);}

The first and last onclick adders does not work.

The second gives the alert "ok_2".

 

But I want also the alers (newID);

Edited by Bogey
Link to comment
Share on other sites

Use javascript closures. when you want to use a variable from one scope in another closures are pretty much the only way (there are other ways but they get messy, ugly, and are usually bad practice)

function addToList(newID, oldID){  var newer = document.getElementById(newID);  var older = document.getElementById(oldID);  newer.innerHTML = older.innerHTML;  newer.classname = "newclass"  newer.onclick = function(){    removeFromList(newID);    }}function removeFromList(newID){  alert(newID);}

you define a wrapper function "inside" the same scope that newID is defined. Since this function can see all the variables in the addToList, it will know about the "newID" even inside the wrapper. Javascript closures aren't about wrapper functions, but its why wrapper functions like this work.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...