I need to change the border color of my HTML <li>
element when the user takes the cursor over the item and also to change the cursor icon when the mouse is over the item. I tried this, but it says "syntax error"
HTML
<li class="post-item-parent-div" onmouseover="onItemHover(this)" >
<!-- More HTML Code -->
</li>
Javascript
function onItemHover(x) {
x.border-top = "12px solid #0084FD";
x.border-left = "12px solid #0084FD";
x.cursor = "pointer";
}
I'm very new to Javascript, so please help out :)
Why not use the :hover
selector?
li.post-item-parent-div:hover
{
border-top: 12px solid #0084FD;
border-left: 12px solid #0084FD;
cursor: pointer;
}
JSFiddle example: https://jsfiddle.net/zt66jf39/
You need to change the css property names like below, as the style names with -
can't be directly used in javascript.
See CSS Properties Reference for the reference names of css properties in javacsript
function onItemHover(x) { x.style.borderTop = "12px solid #0084FD"; x.style.borderLeft = "12px solid #0084FD"; x.style.cursor = "pointer"; }
<ul> <li class="post-item-parent-div" onmouseover="onItemHover(this)"> some code </li> </ul>
But also note that the mouseover event will get triggered when you move to another element within the same parent li
, so you might consider using the mouseenter event
function onItemHover(x) { snippet.log('on over') } function onEnter(x) { snippet.log('on enter'); x.style.borderTop = "12px solid #0084FD"; x.style.borderLeft = "12px solid #0084FD"; x.style.cursor = "pointer"; }
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> <ul> <li class="post-item-parent-div" onmouseover="onItemHover(this)" onmouseenter="onEnter(this)"> some code <span>in span</span> <a href="#">in link</a> </li> </ul>
This will do:
function onItemHover(x) {
x.setAttribute("style", "border-top: 12px solid #0084FD; border-left: 12px solid #0084FD;cursor:pointer;");
}
Add this code
var item = document.getElementById("button");
item.addEventListener("mouseover", func, false);
item.addEventListener("mouseout", func1, false);
function func()
{ // not needed since item is already global,
// I am assuming this is here just because it's sample code?
// var item = document.getElementById("button");
item.setAttribute("style", "background-color:blue;")
}
function func1()
{
item.setAttribute("style", "background-color:green;")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.