Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I reference a createElement variable in a mouseover event. I am trying to show a button that will have an onclick event after a mouseover event.

JavaScript
var lis = document.getElementsByTagName('li');
var element = document.createElement('input');

for (i=0; i<lis.length; i++){ 
   lis[i].onmouseover = function(){ 

	 element.type='Button';
	 element.name = 'Edit'
      // alert(event.clientX+':'+event.clientY);
 
	 this.style.backgroundColor = "red";
      // this.element();

    }; 
    lis[i]. önmouseout = function(){ 
      //alert('Mouse Out');
	this.style.backgroundColor = "white";

    }; 
} 



Thanks in advance
Posted

1 solution

Of course you can, because document.createElement returns DOM element.

The only problem is that your freshly created element does not exist in the DOM of your document: you did not append or insert it in the code you show in your question.

Please see the documentation page demonstrating how to create an element and add it using element.appendChild (for example):
http://reference.sitepoint.com/javascript/Document/createElement[^].

[EDIT]

Of course, to handle an event by the freshly created element, use the variable immediately:

JavaScript
element.onmouseover = function() { /* ... */ }
// and NOT önmouseout or önmouseover


What you are doing in the cycle is not clear: you handle mouse events of different list item elements in the same way; modify properties of the same element element in the same way. Why? Just think about it.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900