Doina Bostan
Doina Bostan

Reputation: 74

Javascript: call different functions according to screen resolutions

I want to call two diferent functions according to screen resolution. I did this thith this code, but the parameters don't change when the user change the width browser. Cand anyone help me? This is the code:

var width=document.body.clientWidth;

function onresize(e) {
  
   width = e.target.outerWidth;
  
   console.log("width 1 is "+ width)
   
}
window.addEventListener("resize", onresize);

console.log("width is "+ width)

if(width>787){
  srcBtn.addEventListener("click", open)
  cls.addEventListener("click", closeBanner)
}else{
  srcBtn.addEventListener("click", divSearch)
}

Upvotes: 0

Views: 277

Answers (3)

Arthur
Arthur

Reputation: 71

It seems to me that you don't really need the resize.

You could just add the test of the document width inside your onClick methodes:

function isWide() {return document.body.clientWidth > 787}

srcBtn.addEventListener("click", function(e) {
  if( isWide() ) { open(e) } else { divSearch(e) } 
});

cls.addEventListener("click", function(e) {
  if( isWide() ) { open(e) }
});

Upvotes: 1

scraaappy
scraaappy

Reputation: 2886

Wrap your listener assignement into a function (which also removes old listeners). Then call this function first on initialisation, and then onresize.

var width=document.body.clientWidth;
var srcBtn = document.getElementById('srcBtn');

function onresize(e) {
    width = document.body.clientWidth;
    console.log("width 1 is "+ width);
    setListeners();
}
window.addEventListener("resize", onresize);
console.log("width is "+ width);
setListeners();

function setListeners(){
    if(width>490){
        srcBtn.removeEventListener("click", divSearch);
        srcBtn.addEventListener("click", open);
//  cls.addEventListener("click", closeBanner);
    }else{
        srcBtn.removeEventListener("click", open);
        srcBtn.addEventListener("click", divSearch);
    }
}

function open () {
    console.log('open');
}
function divSearch () {
    console.log('divSearch');
}
<button id="srcBtn">click me</button>

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You need to use clientWidth inside the event too :

width = document.body.clientWidth;

var width = document.body.clientWidth;

function onresize(e) {

  width = document.body.clientWidth;

  console.log("width 1 is " + width)

}
window.addEventListener("resize", onresize);

console.log("width is " + width)

Upvotes: 0

Related Questions