const_ref
const_ref

Reputation: 4096

How to select a list item only when hovering on the text using Javascript

I create a list item in an unordered list at runtime as follows:

// Javascript code
var items = document.getElementById("list");

var item = document.createElement("li");
item.className = "ItemClass";
item.innerHTML = "Item";
items.appendChild(item);

document.getElementById('list').addEventListener('click', function (event) {
            if ('LI' != event.target.tagName) return;
            // Call a javascript function here
        }, false);

// Css Code

#list 
{
    font-size: 14px;
    color: #069;
}

#list ul
{
    list-style:none;
}

#list ul li 
{
    padding-bottom: 5px;
}

.ItemClass:link
{
    color: #069;
    text-decoration: none;
}

.ItemClass:visited
{
    color: #069;
    text-decoration: none;
}

.ItemClass:hover
{
    color: #000000;
    font-size: 20px;
    text-decoration: none;
}

I would like to be able to format the list so that an item can only be selected/highlighted when the text is directly hovered over, not when hovering over white space etc. beside it. Currently it can be selected and the javascript event is fired even when not directly hovered. As I am making a single app application I do not want the page to refresh and therefore I don't think I could use a href.How can I fix this, thanks!

Upvotes: 0

Views: 104

Answers (2)

dfsq
dfsq

Reputation: 193291

By default UL element is block level element. It means that it takes as much horizontal space as it can. You either make it inline-block of set some specific width (probably better option, but it depends on your case):

ul {
    display: inline-block;
} 

Demo: http://jsfiddle.net/4ckvLrx5/1/

Upvotes: 1

A.Zaben
A.Zaben

Reputation: 681

try using a tag inside the list item and prevent default action

https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Upvotes: 0

Related Questions