Tony Stark Tony Stark - 2 months ago 11
HTML Question

attached event listener not working

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. Could someone please help me out? Thanks in advance for any suggestions!!



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>




Answer

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>