JQuery if statement not working as expecting - javascript

I'm using Bootstrap 3 and creating an if statement with JQuery to make my navbar collapse when anything on the body is clicked, but only when the browser width is less than 992px. When the browser is 992px or wider, I want this function to be ignored. My function below is working as expected, except for the fact that "test" gets logged to the console when the body is clicked on all browser widths when it should only do so when it is less than 992px. Is something wrong with my if statement below?
if ($(window).width() < 992) {
$('body').click(function() {
console.log("test");
$('.navbar-collapse').collapse('hide');
});
};
I updated my code to have the if statement inside of the function, as seen below. It still functions properly and only logs "test" to the console on the correct browser width, but I'm wondering if this is a bad way to do it as the browser will be checking its width on every click even when I don't want it to. Is that a bad way of doing things? Is it better practice to try to get the first code I posted to work?
$('body').click(function() {
if ($(window).width() < 992) {
console.log("test");
$('.navbar-collapse').collapse('hide');
};
});

The second method is the way to go. The first one will only bind the click event if the width is less than 992 when that block of code initially executes.
What if the user resizes the browser after the initial decision to bind/not bind has been made? That's why you need to check the width on every click.

If you bind your click event handler using .bind(), you can use the .resize() event to only have the handler bound when the screen is under your desired width. The .unbind() function does the job. For example:
var collapseNavbar = function() {
console.log("test");//remove when done with testing
$('.navbar-collapse').collapse('hide');
}
$(window).resize(function() {
if($(window).width() < 992) {
$('body').bind('click',collapseNavbar);
} else {
$('body').unbind('click',collapseNavbar);
}
});
This way the check for window width is only done while/after resizing, and not on every click.
The bound function can be named as you wish, just make sure it is indeed named so unbinding can work properly. As the documentation says:
By naming the handler, we can be assured that no other functions are accidentally removed.
I'm not sure if the resize event is raised when the page is loaded, though. You might need to add a little snippet to ensure the behavior is present for a browser window which starts at a width lower than 992px (i.e. if you refreshed the page after resizing, or if you're viewing it on a smartphone). Something like this should do it:
$(document).ready(function() {
if($(window).width() < 992) {
$('body').bind('click',collapseNavbar);
}
});

Related

How to detect window width changes without resizing

I already looked for the .resize() jquery function but the jquery .resize() only triggers when the window is being resized, what i wanted was a trigger that shoots when the width changes for example, instead of changing the browser width the user clicks in the button to maximize and the function fails to trigger, i have a function that fires a function on resize(), is there any function that is like on("windowwidthchanges") ?
You can detect both events and just execute code when it's a width change:
var width = $(window).width();
$(window).resize(function(){
if($(this).width() != width){
width = $(this).width();
console.log(width);
}
});
I've checked Chrome, Firefox and IE11. All 3 browsers trigger the alert when the maximize button is clicked.
$(window).resize(function(){ alert("resized"); });
What, specifically, are you trying to do that this doesn't work for you?
You can move the code to a named function and call it on resize and when clicking the button.
Or, you can trigger the resize when clicking the button:
$("button").on("click", function(){
$(window).trigger("resize");
});
Examples: http://jsfiddle.net/cde7fwrb/
EDIT: I see you were talking about the browser maximise button. Oh well....

What is the correct logic of hiding a DIV the instant its height is below a certain number?

I have a div filled with images.
I have a button that removes images one by one from the div, thus decreasing its height every time.
When the div's height is below 75px in height (implying that it no longer holds any images), I have this jQuery code that is meant to hide the div as soon as the low height is detected:
if ($('#ImageDiv').height() < 75) {
$('#ImageDiv').hide();
}
This code is programmed to activate every time the user clicks that Remove Image button.
Instead, here is what is actually happening: The user clicks the button, thus removing the image, but the div does NOT immediately hide the div despite the height being below 75. Instead, it requires a second click of the button to realize the height is low enough to hide the div.
What is wrong with my logic and how can this problem be fixed?
Without any code that's my better... try to print on console or alert $('#ImageDiv').height() at the end of your function to see what it really sizes.
Are you using an animation to remove the images? If yes, maybe you could check your height value at the complete callback from the animation. Maybe are you evaluating the $('#ImageDiv').height() before the animation has completed?
Hope this helps.
EDITED AFTER COMMENT
With .slideUp() function you can pass a function as second argument (callback). There you can check or do whatever you want:
$('#ImageDiv').slideUp('fast', function() {
// After slideUp is completed, run this...
});
More info here: http://api.jquery.com/slideup/
If you use .remove() function you could check the height with:
$.when($('#your_Removed_DIV_ID').remove()).then(
console.log(
'Height: ' + $('#ImageDiv').height()
)
);
The case might be that you are removing the image from the div after the height check condition. Make sure to do that earlier.
Alternatively, you can simply use if( $('#ImageDiv').has('img').length ) for the presence of img tag inside the div. This would for images less that 75 as well.
This might help you:
$('#remove').on('click', function(){
$('#ImageDiv > img').last().remove(); //remove the last Image
if ($('#ImageDiv > img').length === 0) { //check if there is an image left
$('#ImageDiv').hide();
}
});
Normally I would recommend to cache reused jQuery-Objects, but in this case this would cause an error because an old state is checked.
Side-Note: If this button is within a form-element or a styled anchor-tag you might need to use event.preventDefault() at the beginning of your function.
Demo
You would need to prevent the default activity of button and perform the desired action. http://jsfiddle.net/bcnsk83p/1/
Example:
$("#btn").click(function(e){
e.preventDefault();
$('#ImageDiv img:last-child').remove();
if ($('#ImageDiv').height() < 75) {
$('#ImageDiv').hide();
$('p').text("#ImageDiv is now hidden!");
}
});

Execute javascript code ONLY if width is higher than x pixels

I'm trying to execute a javascript function ONLY if the width is bigger than 1200pixels.
The code I need to execute works, but the check for the screen size doesn't:
window.addEventListener("resize", function(){
if (document.documentElement.clientWidth > 1203) {
<<<some other code that's working>>>
}
}, true);
All this code is in a javascript file outside the document.ready function.
EDIT: When you drag your screen window around, it isn't working like normal css queries. This is the problem. It works if you refresh your page, but if you change the width of your browser, then it doesn't adjust, it needs the reload right now.
That's my issue.
You need to add an else clause to get the behaviour you want. Otherwise the resize event will only work going one way, as you described.
window.addEventListener("resize", function(){
// fire when above 1203
if (document.documentElement.clientWidth > 1203) {
console.log('Greater!');
}
// fire when below 1203
else {
console.log('Smaller!');
}
}, true);
Here's a link to the fixed jsfiddle that planet260 wrote: http://jsfiddle.net/4dnemh2j/4/
Here's my example again: https://jsfiddle.net/9n5hmpua
The problem is the true you're passing to addEventListener.
See the useCapture section here: EventTarget.addEventListener
Events which are bubbling upward through the tree will not trigger a listener designated to use capture
So you want:
window.addEventListener("resize", function(){
if (document.documentElement.clientWidth > 1203) {
<<<some other code that's working>>>
}
}, false); <----change here
You can use jQuery to achieve this
$( window ).resize(function() {
console.log($( window ).width());
var windowwidth = $( window ).width();
if (windowwidth > 500) {
console.log("Greater than 500");
/*Do your work here*/
}
});

window.resize - Won't fire until I've manually changed the browser width

I have a little code snippet here:
$(window).resize(function() {
if ($(window).width() <= 768) {
$('.menu-item-810').click(function () {
$('.squares').slideDown(2000);
});
}
});
That says when the browsers window width is less than or equal to 768px, when you click on the element that has a class of .menu-item-810, slideDown the .squares element.
That is what I want, and it does work.. but only 99.8% correctly.
When the screen width is larger than 768px, the .squares element has a different jQuery effect, it fades in and out, instead of sliding. I needed it to slideDown instead, when in tablet/mobile view, so I wrote the above snippet.
Like I said, it all works, but say I've opened any browser, resized it to 768px or less width, browsed to the site and then click on .menu-item-810. Nothing happens. It's only when I then manually resize the browser again, by any amount, that the jQuery fires. So if I've just resized the browser again, and then click .menu-item-810, the .squares element slides down like expected, but only if I manually resize the browser. I thought that the jQuery would be listening from the start if I wrapped that snippet in $(document).ready() but that doesn't work either, it just has the same behavior as without.
Anyhoo, any help is as always massively appreciated. Hopefully I'm just missing something simple.
Thanks guys!
Actually, this makes no sense? The resize event handler fires thousands of times when the window is resized, and binding a click event handler inside the resize handler will get you thousands of click handlers.
Attach one single click handler, and check the windows width inside it
$('.menu-item-810').click(function () {
if ($(window).width() < 768) {
$('.squares').slideDown(2000);
}
});
Once your javascript has loaded, it needs a resize event to fire in order to trigger your code. - it doesn't know if the window has been resized prior to the handler being initialised.
Put the same snippet in your document.ready() function to do an initial check for window size:
$(document).ready(function() {
if ($(window).width() < 768) {
$('.menu-item-810').click(function () {
$('.squares').slideDown(2000);
});
}
});
In the order of your code, it is first checking the window size, and only then, if it is small, adds your event handler.
It sounds like what you want is to always call the event handler, and then change the action depending on the side.
$(window).resize(function() {
$('.menu-item-810').click(function () {
if ($(window).width() <= 768) {
$('.squares').slideDown(2000);
}
});
});
Actually, now that i think some more, you don't even need to set the handler upon resize. Just set it on document load, and check the size when it gets clicked.
$(document).ready(function() {
$('.menu-item-810').click(function () {
if ($(window).width() <= 768) {
$('.squares').slideDown(2000);
}
});
});

need an event triggered if the page has scrolled 200px down (jQuery)

I want to show and hide a piece of code if i scroll and the page is for example half way, i have tried to use window scroll but this doesnt works(no errors, clean code, different browsers, different jQuery versions), but this doesn't trigger anything, so i am looking for a better way to show and hide a div if i scrolldown.
used this to trigger an event(not working)
$(window).scroll(function(){
alert('works')
});
Try using the window.onload function (that's how they use it in jQuery examples):
window.onload = (function(){
$(window).scroll(function () {
if( $(window).scrollTop() > 200 ) {
// Display something
}
})
})

Categories

Resources