rockleegustavo
rockleegustavo

Reputation: 25

javascript events handlers don't work properly

I have some problem with javascript event handlers and I really want to know what am I doing wrong. Here's the thing, I want to alert the hovered div's width, but as soon as the page is loaded, the alert appears.

Here's the HTML:

<div id="mainContainer">  
    <div id="container_1" style="width:200px"></div>  
    <div id="container_2" style="width:100px"></div>  
    <div id="container_3" style="width:300px"></div>  
    <div id="container_4" style="width:150px"></div>  
</div>

and here's the js:

dataRetrieving = {
    getWidth:function(id){
        var box = document.getElementById(id);
        var tempResult = box.style.width;
        return tempResult;
    }
}
var container = document.getElementById("container_1");
container.onmouseover = function(){
    alert(dataRetrieving.getWidth("container_1"));
};

already answered, thanks :D

I'd appreciate any tip you guys give me.

Thanks in advance!

Upvotes: 2

Views: 94

Answers (2)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

container.onmouseover = dataRetrieving.getWidth("container_1");

You are calling that function there that's why it's alerting on the page load.

Upvotes: 1

ziesemer
ziesemer

Reputation: 28697

You would need to set your onmouseover with something like this:

container.onmouseover = function(){
  dataRetrieving.getWidth("container_1");
};

In your current code, the event handler (set to container.onmouseover) is set to the result of dataRetrieving.getWidth(...) - which is nothing, since getWidth doesn't currently return anything. This is also causing the alert to appear immediately, since the function is executing immediately. (In order to be valid, it would have to return another function.)

Upvotes: 2

Related Questions