Reputation: 83
I have a problem for a particular div element and its id. I want to add hover link style, but how to do this? I do not quite understand. My example:
<a href="#" onmouseover="changeDiv('image_1')" onmouseout="defaultDiv('image_1')">Home</a>
And the script processing the addition of style:
<script>
function changeDiv('image_1'){
document.getElementById('image_1').style.width="230px";
document.getElementById('image_1').style.height="162px";
document.getElementById('image_1').style.top="0px";
}
</script>
Tell me why this code does not work for my id image_1
?
Upvotes: 0
Views: 103
Reputation: 33865
The problem is that you specify a string literal instead of variable as the parameter of the function, which will cause a syntax error.
Try modifying your function to something like this:
<script>
function changeDiv(id){
document.getElementById(id).style.width="230px";
document.getElementById(id).style.height="162px";
document.getElementById(id).style.top="0px";
}
</script>
Now you can pass any id you want to the function when calling it.
Cache a reference to the element for performance:
For performance, you can also cache the element in a variable, so you don't have to look it up in the DOM three times:
<script>
function changeDiv(id){
var elm = document.getElementById(id);
elm.style.width="230px";
elm.style.height="162px";
elm.style.top="0px";
}
</script>
Modify multiple elements at the same time:
To modify multiple elements at the same time, you can call the function multiple times with different parameters:
onmouseover="changeDiv('image_1'); changeDiv('image_2');"
Or you can alter the function to take an array of strings with the IDs of elements.
<script>
function changeDivs(ids){
for(var i = 0, len = ids.length; i < len; i++) {
var elm = document.getElementById(ids[i]);
elm.style.width="230px";
elm.style.height="162px";
elm.style.top="0px";
}
}
</script>
You can then call it like so:
onmouseover="changeDivs(['image_1', 'image_2'])"
Upvotes: 7
Reputation: 55
in function attribute must be var not string and you must called this var for example
function myfunc(d){ //d is varble
alert(d);
}
Upvotes: 0
Reputation: 600
Try this...
<a href="#" >
<div id='image_1' onmouseover="changeDiv('image_1')" onmouseout="defaultDiv('image_1')" style="width:100px; height:18px; border-style:ridge;">
Home
</div>
</a>
If you just want pointer when mouse over.
** add DIV border border-style:ridge
for test...
** Create ID for your Tag.
This JS Script
function changeDiv(IDS){
document.getElementById(IDS).style.width="230px";
document.getElementById(IDS).style.height="162px";
document.getElementById(IDS).style.top="0px";
}
Upvotes: 0