How can combine this JS code? I now have a duplicate code and don't know how to combine the window.width() together with the resize function. The function must execute under 1100px and on resize under 1100px.
if($(window).width() <= 1100){
// do something if window is less than 1100px
$(window).resize(function() {
// I have the same code here now a above! How can I combine it?
});
} // end window.width()
Try to invert your logic:
$(window).on("load resize", function() {
if($(this).width() <= 1100){
// do something
}
});
additionally you can add both load resize events like above.
If you want to trigger it also on DOM ready than:
function myResizeFunction() {
if($(window).width() <= 1100){
// do something
}
}
$(myResizeFunction); // Do on DOM ready
$(window).on("load resize", myResizeFunction); // And also on load and resize
Related
On the desktop sizes, my navbar brand includes only one larger image. But on the mobile sizes I want that larger image to be replaced with two smaller images. For that, I have used jQuery and when I check it on the mobile it looks just how I wanted to. But the problem is that as I change my browser's size the image is not being replaced in real time. Is there a way I could achieve this?
$(document).ready(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="assets/images/Llogo AIP.png"><img src="assets/images/CoA RKS.png">');
}
});
<a class="navbar-brand" href="index.html"><img src="assets/images/logo.png"></a>
To get the code to be executed on resizing the window you should use .resize():
The resize event is sent to the window element when the size of the browser window changes.
$(window).resize(function() {....
Demo:
$(document).ready(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="https://homepages.cae.wisc.edu/~ece533/images/pool.png"><img src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png">');
}
$(window).resize(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="https://homepages.cae.wisc.edu/~ece533/images/pool.png"/><img src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png"/>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="navbar-brand" href="index.html"><img src="assets/images/logo.png"></a>
This behavior is because the image is only replaced at document ready, aka when the document has finished loading.
If you want to change the images on window resize you need the resize event handler, as Mamun pointed out.
In that case you probably also want to switch back to the original image when you make the screen larger. I would make a separate function to handle setting the correct images and call it on window resize and on document ready. For example:
$(document).ready(function() {
setNavImages();)
});
$(window).resize(function(){
setNavImages()
});
function setNavImages(){
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="assets/images/Llogo AIP.png"><img src="assets/images/CoA RKS.png">');
}else{
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="[your original image here]">');
}
}
Like #Mamun said and call it on document ready
or better use bootstrap hidden-xs visible-md classes
$(document).ready(function() {
$(window).resize(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="assets/images/Llogo AIP.png"><img src="assets/images/CoA RKS.png">');
}
});
$(window).resize(); // call it here after define it
});
<a class="navbar-brand" href="index.html"><img src="assets/images/logo.png"></a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
With this code the navbar will change like you want, on every resize, for example.
$(document).ready(function() {
navbarBrandContent = $('.navbar-brand').html();
changeNavbarBrand();
});
$(window).resize(function() {
changeNavbarBrand();
});
function changeNavbarBrand() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="assets/images/Llogo AIP.png"><img src="assets/images/CoA RKS.png">');
} else {
$('.navbar-brand').html(navbarBrandContent);
}
}
I have search a lot but couldn't find proper solution. I am going to element prepend/append to another element after certain width. But it works after resize browser only.
I have found this solution but still not helpful
How can i achieve?
$(window).on("resize", function(event){
$vWidth = $(this).width();
$('#test').html($vWidth)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
To make it work on Load, try
$( window ).load(function() {
// Run code
});
and on resize try
$(window).on("resize", function(event){
$vWidth = $(this).width();
$('#test').html($vWidth)
});
you can write the conditions like $(window).width() < 700 inside the methods
If you want the code to run when the page loads you can also have it triggered when the page is ready.
I would convert the relevant portion of your code into a function to avoid duplication of codes.
Demo working sample:
https://jsfiddle.net/j6nermyL/9/
Sample JS code:
$(document).ready(function() {
checkWidth();
});
$(window).on("resize", function(){
checkWidth();
});
function checkWidth(){
$vWidth = $(window).width();
$('#test').html($vWidth);
//Check condition for screen width
if($vWidth < 700){
$('#msg').html("Width: Less than 700");
}else{
$('#msg').html("Width: More than 700");
}
}
Sample HTML code:
<div id="test">Test</div>
<br>
<div id="msg"></div>
Update: I modified my JSFiddle with the check condition.
Update 2: The width is now retrieved from $(window)
Reference:
jQuery Ready event
API documentation for .ready()
Use load, if you want to do action on page load
Try this:
$(window).on("resize", function(event){
$vWidth = $(this).width();
$('#test').html($vWidth)
});
$(window).on("load", function(event){
$vWidth = $(this).width();
$('#test').html($vWidth)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
function dropdownHover() {
jQuery('ul.nav li.dropdown').hover(function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});
}
$(window).on('resize', function(event){
var windowSize = $(window).width();
if(windowSize > 992){
dropdownHover();
}
});
I need this function dropdownHover() to fire only when window is greater than 992px, both on load and on resize, else if window is < 992px, both on load or on resize i dont want to fire this function on hover i want regular bootstrap dropdown on click. I tried to do this with css but i cant add animation on dropdown because its just display: none/block. I also tried to add class on resize to fire this function if element has that class else dont but it doesnt work either.
Edit: Final working version
$('.dropdown').on('mouseenter', function(){
if(!$(this).is('.open') && $(window).data('wide'))
$('.dropdown-menu', this).dropdown('toggle').hide()
.stop(true, true)
.delay(200)
.fadeIn(function(){
this.style.display = '';
}).find('a').on('touchstart click', function (e) {
e.stopPropagation();
});
}).on('mouseleave', function(){
if($(this).is('.open') && $(window).data('wide'))
$('.dropdown-menu', this).dropdown('toggle');
});
$('.dropdown').on('click', function(e){
if( $(window).data('wide')) {
$('.dropdown-menu', this).dropdown('toggle');
} else {
$('.dropdown-menu', this)
.stop(true, true).slideToggle()
.closest('.dropdown').removeClass('open');
}
});
// not entirely necessary. Not sure which is faster: this or just checking the width in all three places.
$(window).on('resize', function(){
$(window).data('wide', $(window).width() > 992);
// reset the open menues
$('.dropdown').removeClass('open');
$('.dropdown-menu').css({
display: '',
left: '',
position: '',
});
// because we are checking the width of the window, this should probably go here although this really should be a media query style
$('.dropdown-menu.pull-center').each(function() {
var menuW = $(this).outerWidth();
if ($(window).width() > 1000) {
$(this).css({
left: - menuW / 2 + 60 + 'px',
position: 'absolute'
});
} else {
$(this).css({
left: '',
position: ''
});
}
});
}).trigger('resize');
Initial Solution
Your question is twofold. First, you need it to not show the menu at smaller sizes. For that, you check on resize what the window width is. The problem is that it only works once. It triggers the event listeners for hover and it doesn't kill those event listeners if the screen is then larger at some point. For that, you can set a flag. There are a lot of ways to do this, but for my answer, I've chosen to use jQuery .data() method.
$(window).on('resize', function(event){
var windowSizeWide = $(window).width() > 600; // reduced for testing purposes
jQuery('ul.nav li.dropdown').data('dropdown-enabled', windowSizeWide);
}).trigger('resize');
Then when we listen for the hover events (which are mouseenter and mouseleave events), we simply return out of the function if the screen is too small.
jQuery('ul.nav li.dropdown').on('mouseenter', function() {
if(!jQuery(this).data('dropdown-enabled')) return;
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}).on('mouseleave', function() {
if(!jQuery(this).data('dropdown-enabled')) return;
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut();
}).find('.dropdown-menu').hide();
Finally, you also want the event to trigger on load. You can do that by simply adding .trigger('resize') as seen in the first snippet. You can see a functioning demo here: http://jsfiddle.net/jmarikle/xw9Ljshu/
Possible Alternative Solution
Alternatively, you can also use CSS to handle this with media queries. The simplest way to do this is to force display: none on smaller screens. I don't recommend completely hiding the element because it becomes inaccessible at that point, but this is the general idea:
#media(max-width: 600px) {
ul.dropdown-menu {
display:none !important;
}
}
Note that !important is used because jQuery adds inline styles when you fadeIn or fadeOut.
Second demo: http://jsfiddle.net/jmarikle/xw9Ljshu/1
window.screen.availWidth to get the window size. i am yet not tested your code.But i think this will ok.
function dropdownHover() {
jQuery('ul.nav li.dropdown').hover(function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});
}
$(document).ready(function(){
$(window).on('resize', function(event){
var windowSize = window.screen.availWidth;
if(windowSize > 992){
dropdownHover();
}
});
})
I want java script functionality only in mobile device 767px.
This is my code
$('#my-btnn').click(function () {
$('#mobile-login').hide();
$('#user-settings').slideToggle('fast');
});
You can simply check window width in order to determine if function should work or not:
$('#my-btnn').click(function () {
if ($(window).width() < 767) {
$('#mobile-login').hide();
$('#user-settings').slideToggle('fast');
}
});
You can bind your click by checking your resolution. Use onResize and check by screen.width
$(window).resize(function() {
if (screen.width <= 767) {
$('#my-btnn').bind('click', function () {
$('#mobile-login').hide();
$('#user-settings').slideToggle('fast');
});
}
});
And you can check if you were binded early.
Or you can just to add this checking in onReload
I have a menu that is hidden in an accordion when viewing on screens less than 600px.
On screens larger than 600px the menu is visible.
jsfiddle- http://jsfiddle.net/ashatron/zbzqoz2f/
it works ok, but when i resize the window to be greater than 600px, then go back to less than 600px then press view sitemap it loops the animation multiple times.
I think its running the function for every resize event, which is queing up the accordion and then looping it. But I'm not sure how best to order the syntax to get it to work.
Any help would be appreciated!
footernavmenufn = function() {
var current_width = $(window).width();
if (current_width < 600) {
$('.footer-accordion-head').show();
$('.footer-accordion-body').hide();
$('.footer-accordion-head').click(function () {
$(".footer-accordion-body").slideToggle('400');
// console.log('hmmm');
return false;
}).next().hide();
} else {
$('.footer-accordion-head').hide();
$('.footer-accordion-body').show();
}
};
$(document).ready(function () {
footernavmenufn();
});
$(window).resize(function(){
footernavmenufn();
//console.log('OMG-WHY-YOU-NO-WORK');
});
The issue is that everytime window is resized and the condition is met, you're binding a new click event handler, so after a while there'll be multiple event handlers causing chaos. Ideally your code should be something like
$(document).ready(function () {
$('.footer-accordion-head').click(function () {
$(".footer-accordion-body").slideToggle('400');
console.log('hmmm');
return false;
});
$(window).resize(footernavmenufn);
footernavmenufn(); // or $(window).trigger("resize");
});
footernavmenufn = function () {
var current_width = $(window).width();
if (current_width < 600) {
$('.footer-accordion-head').show();
$('.footer-accordion-body').hide();
} else {
$('.footer-accordion-head').hide();
$('.footer-accordion-body').show();
}
};
Updated Fiddle
Why do you have this code? Crazy one. Remove it:
if (current_width < 600) {
$('.footer-accordion-head').show();
$('.footer-accordion-body').hide();
$('.footer-accordion-head').click(function () {
$(".footer-accordion-body").slideToggle('400');
return false;
}
move the click declaration into the $(document).ready function.
at the moment everytime you resize the page that click function is being added again - so the repeat is once per page resize.
forked jsfiddle with change