Tutorial :Assign javascript function to a dom element



Question:

i'm using the mshtml library for parsing out html via MSHTML.HTMLDocument.

my question: is there a way to assign a javascript function to a dom element? i've tried something like:

div.onmouseover = "function(){alert('mouseover')}"

and

div.setattribute "onmouseover" , "function(){alert('mouseover')}"

without success (no error but no effect either). anyone knows if its possible?

thx


Solution:1

Always use a function, rather than attaching a string of code in your javascript. You can do this by assigning an anonymous function. The function receives an event object as it's only argument, which has information about the event, if you need to know the x/y positions of where the mouse was.

div.onmouseover = function(event) {      //do stuff  };  


Solution:2

Have you tried not using anonymous functions? For example instead of

div.onmouseover = "function(){alert('mouseover')}"  

Use something like

div.onmouseover = "alert('mouseover');"  


Solution:3

try using the

<script>  

tag in your string


Solution:4

You are defining the function but not invoking it. You have to invoke the function by including the invocation parentheses. Use

div.setattribute "onmouseover" , "function(){alert('mouseover')}()"  


Solution:5

div.onmouseover = function(){alert("mouseover")}  


Solution:6

Try this:

div.setattribute "onmouseover" , "alert('mouseover');"  


Solution:7

try to use

button.onclick = new Function(“someFunctionName(‘input” + counter + “‘)”);

instead of function(){alert("mouseover") , this will work for dynamic created controls

note the spelling difference between 'function' and 'new Function'


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »