Thor
Thor

Reputation: 10028

Attached event listener on mouseover

I'm very new to Javascript and is trying to attach an anonymous function to an event listener. What the function does is that when mouseover the first element, a message will be displayed in the second element depending on the length of the text within the first element.

However, when I hover my mouse over the first element, nothing happens. Because I'm new to JavaScript, I'm not sure what I did wrong.

    function checkLength(event, minLength){
        var el, elementTwo;
        el = event.target;
        elementTwo = el.nextSibling;
        
        if(el.value.length < minLength){
            elementTwo.innerHTML = "not enough";
        } else {
            elementTwo.innerHTML = "enough";
        }
    }
    
    var elUserName = document.getElementById("one");
    elUserName.addEventListener("mouseover", function(event){
        checkLength(event, 5);
    }, false);
    <div>
        <div id="one">Bob</div>
        <div id="two"></div>
    </div>

Upvotes: 0

Views: 205

Answers (1)

MinusFour
MinusFour

Reputation: 14423

To access the text of the element you use textContent. value is for inputs.

Also, you need to select the next element sibling, not just the next sibling node.

function checkLength(event, minLength){
        var el, elementTwo;
        el = event.target;
        elementTwo = el.nextElementSibling;
        
        if(el.textContent.length < minLength){
            elementTwo.innerHTML = "not enough";
        } else {
            elementTwo.innerHTML = "enough";
        }
    }
    
    var elUserName = document.getElementById("one");
    elUserName.addEventListener("mouseover", function(event){
        checkLength(event, 5);
    }, false);
<div>
        <div id="one">Bob</div>
        <div id="two"></div>
    </div>

Upvotes: 2

Related Questions