0

On Resize, I either call desktop Or mobile. I have a click function in each and they both seem to be running, if it was in desktop and then changes to mobile. I need to turn off desktop function if the mobile function is true and vice versa.

Here is a basic version of my code.

Screen_size()
$(window).resize(function() {
 Screen_size()
});
function Screen_size(){
 var w = $(window).width();
 if (w <= 710){
 Mobile();
 }
 if (w > 710){
 Desktop();
 }
}
function Mobile(){
 console.log('Mobile');
 $( "#open" ).click(function(e) {
 console.log('Open Mobile');
 });
}
function Desktop(){
 console.log('Desktop');
 $( "#open" ).click(function(e) {
 console.log('Open Desktop');
 });
}
Barbara Laird
12.7k2 gold badges48 silver badges58 bronze badges
asked Oct 18, 2016 at 0:11
8
  • Well, the resize event happens thousands of times when you resize the browser, maybe even millions of times, and every single time you add another click event handler, and it adds up. Commented Oct 18, 2016 at 0:12
  • Thanks that's good to know whats the best option to remove it? Commented Oct 18, 2016 at 0:13
  • Checking the window size isn't really very accurate, I could have a small browser window open on my 27" screen, and you'd think I was on my phone. Anyway, it's really an X/Y problem, what you should be doing is just checking the window size when you click -> jsfiddle.net/adeneo/gpyeyqgb Commented Oct 18, 2016 at 0:16
  • 1
    Either you're on a mobile phone, or you're on a desktop, it doesn't suddenly change. Commented Oct 18, 2016 at 0:22
  • 1
    You can say $("#open").off("click").click(...) to remove the previous click handler and then bind a new one, but in my opinion it would be better to just bind a single click handler once and move the if test inside the click handler (and not have a resize handler). Commented Oct 18, 2016 at 0:25

1 Answer 1

3

No need for window resize .. just make a click event like this

$( "#open" ).on('click', Screen_size);
 
function Screen_size(){
 var w = $(window).width();
 (w <= 710) ? Mobile() : Desktop() ;
}
function Mobile(){
 console.log('Open Mobile');
}
function Desktop(){
 console.log('Open Desktop');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="open">Click</button>

answered Oct 18, 2016 at 0:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.