Omar Gonzalez
Omar Gonzalez

Reputation: 1147

.onclick event listener over div running instantly after page load

this is probably a nooby question but this scrip is killing me: The script is suppose to change the div weight with an event listener while mouse click. The function changeWidth(i) works just fine. The problem is the event listeners trigger automatically when the page is loaded, and then it stop working. There is no console error.

var tile1 = document.getElementById("project_tile_01");
var tile2 = document.getElementById("project_tile_02");
var tile3 = document.getElementById("project_tile_03");

tile1.onclick = changeWidth(1);
tile2.onclick = changeWidth(2);
tile3.onclick = changeWidth(3);

function changeWidth(i){
    if(i==1){
        tile1.style.width=(200+"px");
        tile2.style.width=(150+"px");
        tile3.style.width=(150+"px");
        tile4.style.width=(150+"px");
        tile5.style.width=(150+"px");
        tile6.style.width=(150+"px");
    }else if(i==2){
        tile1.style.width=(150+"px");
        tile2.style.width=(200+"px");
        tile3.style.width=(150+"px");
        tile4.style.width=(150+"px");
        tile5.style.width=(150+"px");
        tile6.style.width=(150+"px");
    }else if(i==3){
        tile1.style.width=(150+"px");
        tile2.style.width=(150+"px");
        tile3.style.width=(200+"px");
        tile4.style.width=(150+"px");
        tile5.style.width=(150+"px");
        tile6.style.width=(150+"px");
}

I´m not sure if this is a problem of load order, This being really a minimal page the script is running with the < script > tag at the end of the page. Thanks in advance.

Upvotes: 0

Views: 146

Answers (3)

Suman Bogati
Suman Bogati

Reputation: 6349

This tile1.onclick = changeWidth(1); would invoked when body is being onload as plalx said. you can also do something like this.

This will be triggered only when the element would be clicked.

tile1.onclick = function (){
    changeWidth(1);
};

tile2.onclick = function (){
    changeWidth(2);
};

tile3.onclick = function (){
    changeWidth(3);
};

Upvotes: 1

Phil Perusse
Phil Perusse

Reputation: 51

You need to wrap your changeWidth call in a function.

tile1.onclick = function(){changeWidth(1);}

Upvotes: 1

plalx
plalx

Reputation: 43728

tile1.onclick = changeWidth(1);

You are immediately invoking the function with () and the result of the function which is undefined gets assigned to tile1.onclick.

Here's what you can do instead:

tile1.onclick = changeWidth.bind(null, 1);

Upvotes: 1

Related Questions