jQuery window resize and less than certain width - javascript

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>

Related

Updating the HTML on real time using jQuery

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);
}
}

Responsive Mobile Menu

I have a function that applies a class to the html element and also detects if a drop down has been clicked below the width of 900px.
When I resize the browser from desktop view to below 900px I find occasionally that the dropdown class "active-hit" doesn't get applied - meaning that the menu won't open. Any ideas why this might be? I have to reload the page to make it work in mobile view.
// Add Mobile View Class to HTML ELEMENT below 900px
(function($) {
var $window = $(window),
$html = $('html');
$dropdown = $('.dropdown-nav > a');
function resize() {
if ($window.width() < 900) {
$dropdown.on('click', function(e){
$(this).parent().toggleClass('active-hit');
e.preventDefault();
e.stopPropagation();
});
return $html.addClass('mobile-view');
} else {
$html.removeClass('mobile-view');
$dropdown.parent().removeClass('active-hit');
}
}
$window
.resize(resize)
.trigger('resize');
})(jQuery);
As I mentioned in a comment, window resize will not trigger your function, but if You want to do so in testing purposes then you can try to use this:
$(window).resize(function() {
resize();
});
And here is working fiddle for you

Combine .width() and .resize() into one function

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

jQuery css height not applying

For some reason the height is not being set in this piece of code
jQuery(document).ready(function() {
jQuery('#main-content').css({'height': ((jQuery(window).height()))+'px'})
jQuery('#nav-icons a').click(function(){
jQuery('#nav-icons a').removeClass("active-icon");
jQuery(this).addClass( "active-icon" );
var toLoad = jQuery(this).attr('href')+' #main-content';
var toLoadSlider = jQuery(this).attr('href')+' #homepage-slider';
jQuery('#main-content , #homepage-slider').fadeOut(1000, loadContent);
function loadContent() {
jQuery('#homepage-slider').empty().load(toLoadSlider)
jQuery('#main-content').empty().load(toLoad,'',showNewContent())
}
function showNewContent() {
jQuery('#main-content , #homepage-slider').css({'height': ((jQuery(window).height()))+'px'}).hide().fadeIn(2000).removeAttr('id class');
}
return false;
interestingly, the exact same line of code in the showNewContent() does set the height.
The only logical reason for this is that jQuery('#main-content') in your first line is not the actual jQuery object representation of the DOM element of your choice.
You will have to figure that out yourself as to why things turn out this way.
Assuming that you have
<div id="main-content">
... content
</div><!--main-content-->
This should do the trick :
var windowHeight = jQuery(window).height();
jQuery(document).ready(function ($) {
$('#main-content').css({
height: windowHeight
});
// other scripts
}); // ready
JSFIDDLE

whats wrong with this code? im trying to change the height of each section to the height of window

whats wrong with this code? im trying to change the height of each section to the height of window.
function setsize()
{
var w=$(window).width();
var h=$(window).height();
var sections = new Array("home","about","skills");
for (var i=0;i<3;i++)
{
var element = document.getElementById(sections[i]);
$(element).height(h);
}
}
$(window).ready(function() {
setsize();
});
$(window).resize(function() {
setsize();
});
here is sample of the markup:
<section id="#home">
<h1>..................</h1>
</header>
Seems like a strange way to do that ?
$(window).on('resize load', function() {
$('#home, #about, #skills').height( $(this).height() );
});
You have to update the variables when the window changes size, i.e. inside the resize function
EDIT:
You'll also need a DOM ready handler, and window.onload isn't always triggered when doing it that way, so just do the same thing on DOM ready, like so :
$(function() {
$('#home, #about, #skills').height( $(window).height() );
$(window).on('resize', function() {
$('#home, #about, #skills').height( $(this).height() );
});
});
FIDDLE

Categories

Resources