jQuery function on resize and on load without copy/pasting - javascript

I have the following piece of jQuery that checks the width of the browser on load, and runs accordingly. But to make sure the div keeps the right size when the browser-width is changed, I have placed the same piece of code in $(window).resize(function() {..});.
This seems very weird and unnecessary, so I'm wondering how I can place the code only once and have it run on both .resize and on load.
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
$('.banner_image').show();
$('.banner_image').height($('.banner .span3').height());
$('.banner .span12 img').hide();
}
else {
$('.banner_image').hide();
$('.banner .span12 img').show();
}
$(window).resize(function() {
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
$('.banner_image').show();
$('.banner_image').height($('.banner .span3').height());
$('.banner .span12 img').hide();
}
else {
$('.banner_image').hide();
$('.banner .span12 img').show();
}
});

You can trigger the event after binding the event:
$(window).resize(function() {
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
$('.banner_image').show();
$('.banner_image').height($('.banner .span3').height());
$('.banner .span12 img').hide();
}
else {
$('.banner_image').hide();
$('.banner .span12 img').show();
}).resize();//resize to trigger on load
Working Demo

Just store the function in a variable and execute it everytime you want to:
$(window).load(function() {
wFunc();
});
$(window).resize(function() {
wFunc();
});
var wFunc = function() {
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
$('.banner_image').show();
$('.banner_image').height($('.banner .span3').height());
$('.banner .span12 img').hide();
}
else {
$('.banner_image').hide();
$('.banner .span12 img').show();
}
}

Related

Html attribute control with if

my img has 3 attribute but if has one attribute (data-web-src,data-tablet-src,data-mobil-src) than set my src than one of them attribute is that possible ?
please click to see on codepen
function noLazyImages(e) {
$(e + '.lazy_res').attr('src', function(_, oldSrc) {
var elData = $(this).data(),
winWidth = $(window).width();
if (winWidth >= 768 && winWidth < 960) {
return elData['webSrc']
} else if (winWidth < 768 && winWidth >= 480) {
return elData['tabletSrc']
} else if (winWidth < 480) {
return elData['mobilSrc']
} else if (winWidth > 960) {
return elData['webSrc']
}
})
}
$(document).ready(function() {
noLazyImages("body img");
})
img {
width: 300px;
}
<img class="lazy_res" data-web-src="http://image.prntscr.com/image/bdf1d94b64104ef2acd2ceee19882cd1.jpg" data-mobil-src="http://image.prntscr.com/image/caa51ab4900448589201207e57b2630f.jpg" data-tablet-src="http://image.prntscr.com/image/4b2862a292b543139daa7805a58c17fd.jpg"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I think the following code will do what you want.
I removed the data-tablet-src from the img tag which is there in the question snippet so that you can run both and compare the results.
Logic
if(elData['tabletSrc']) will be false if elData['tabletSrc'] is not present. So it will return return elData['webSrc'] instead.
function noLazyImages(e) {
$(e + '.lazy_res').attr('src', function(_, oldSrc) {
var elData = $(this).data(),
winWidth = $(window).width();
if (winWidth < 768 && winWidth >= 480) {
if(elData['tabletSrc']){
return elData['tabletSrc'];
}
} else if (winWidth < 480) {
if(elData['mobilSrc']){
return elData['mobilSrc'];
}
}
return elData['webSrc'];
});
}
$(document).ready(function() {
noLazyImages("body img");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="lazy_res" data-web-src="http://image.prntscr.com/image/bdf1d94b64104ef2acd2ceee19882cd1.jpg" data-mobil-src="http://image.prntscr.com/image/caa51ab4900448589201207e57b2630f.jpg"
/>
Your script work fine you just need to add listener to window resize event:
$(document).ready(function() {
noLazyImages("body img"); // on Document ready
$( window ).resize(function() {
noLazyImages("body img"); // on window Resize
});
})

how to get and set data variable with jquery?

my image has data-web-src, data-tablet-src and data-mobil-src if my img tag has .lazy_res class instead of .lazyload then set value of data-web-src to src on web, but if screen (or device) is tablet than set data-tablet-src value's to src I want to do this for all images on my web page but I can’t find a solution here you are my code
$(document).ready(function() {
function noLazyImages(e) {
var getWebSrc = $(e).attr("data-web-src");
var getTabletSrc = $(e).attr("data-tablet-src");
var getMobilSrc = $(e).attr("data-mobil-src");
if ($(".box img").hasClass("lazy_res")) {
if ($(window).width() > 960) {
$(e).attr("src", getWebSrc);
} else if ($(window).width() < 768) {
$(e).attr("src", getTabletSrc);
}else if ($(window).width() < 480) {
$(e).attr("src", getMobilSrc);
}
} else {
// do nothing..
}
}
noLazyImages(".box img");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<img class="lazy_res" data-web-src="http://image.prntscr.com/image/bdf1d94b64104ef2acd2ceee19882cd1.jpg" data-mobil-src="http://image.prntscr.com/image/caa51ab4900448589201207e57b2630f.jpg" data-tablet-src="http://image.prntscr.com/image/4b2862a292b543139daa7805a58c17fd.jpg"/>
</div>
you need to loop over all of them and get and set instance specific values
Can do it using attr(function)
function noLazyImages(e) {
$(e + '.lazy_res').attr('src', function(_, oldSrc) {
var elData = $(this).data(),
winWidth = $(window).width();
if (winWidth > 960) {
return elData['webSrc']
} else if (winWidth < 768 && winWidth >=480) {
return elData['tabletSrc']
} else if (winWidth < 480) {
return elData['mobilSrc']
}
})
}
DEMO

Menu-bar in responsive design disappears

I am working on a responsive design template where the horizontal menu-bar will convert into an icon to save space. Basically I have created 3 media queries, i.e. > 800px, betweeen 500 to 800px and less than 500px.
.
It is working fine, but when the windowWidth of the screen reaches the range of 484px to 500px, the menu-bar just disappears! You can go to the link to view the test page : http://www.acetraining.com.sg/responsive1/
// JavaScript Document
var windowSize = "";
var windowWidth = 0;
var actualSize = 0;
$(document).ready(function (e) {
checkBrowserSize();
setInterval("checkBrowserSize()", 100);
$("a.mobile_menu").on("click", function () {
var navHeight = $("nav").height();//finding current height of navigation
var newNavHeight = $("nav div").height();
//mobile screen
if (navHeight == 0) {
$("nav").animate({"height": newNavHeight + "px"}, 500);
$(this).addClass("selected");
}
//retract back to 0
else {
$("nav").animate({"height": "0px"}, 500);
$(this).removeClass("selected");
}
});
});
function checkBrowserSize() {
windowWidth = window.outerWidth;
var contentWidth = $("body").width();
var sizeDiff = windowWidth - contentWidth;//size of scrollbar
actualSize = windowWidth - sizeDiff;
if (actualSize > 800) {
newWindowSize = "large";
}
if (actualSize <= 800 && actualSize > 500) {
newWindowSize = "medium";
}
if (actualSize <= 500) {
newWindowSize = "small";
}
//display out
$("h1").html(windowWidth + "(" + contentWidth + "(contentWidth) + " + sizeDiff + "(sizeDiff)) is " + newWindowSize);
if (windowSize != newWindowSize) {
windowSize = newWindowSize;
//invoke changeNav
changeNav();
}
else {
//append the word no change
$("h1").append("--no change--");
}
}//end of checkBrowserSize()
function changeNav() {
if (windowSize == "large") {
$("nav").css("height", "auto");
}
else if (windowSize == "medium") {
$("nav").css("height", "auto");
}
else if (windowSize == "small") {
$("nav").css("height", "0px");
$("a.mobile_menu").removeClass("selected");//load in the first image of the mobile menu when you resize to small
}
}//end of changeNav()
I suspect the problem lies in my javascript file. I have attached the codes for your perusal:
I am hoping there is a way to show the menus between these ranges.
The media query in screen_layout_large.css css file is hiding the mobile menu. Either edit the media query to give a min-width or show the mobile menu as follows in changeNav function.
function changeNav() {
if (windowSize == "large") {
$("nav").css("height", "auto");
}
else if (windowSize == "medium") {
$("nav").css("height", "auto");
}
else if (windowSize == "small") {
$("nav").css("height", "0px");
$("a.mobile_menu").show().removeClass("selected");//load in the first image of the mobile menu when you resize to small
}
}

Reload page when window passing certain multiple widths

I need the page reload only if the browser window passing width 300px or 769px or 1024px
There is a similar question to my request (http://goo.gl/46jjzH) but the only problem with the approved answer is that the page reload after passing just 769px, I need to do the same with 3 different sizes 300px or 769px or 1024px not just 769px.
The two codes that works only with one certain width from http://goo.gl/46jjzH
First code by #Roko C. Buljan
var ww = $(window).width();
var limit = 769;
function refresh() {
ww = $(window).width();
var w = ww<limit ? (location.reload(true)) : ( ww>limit ? (location.reload(true)) : ww=limit );
}
var tOut;
$(window).resize(function() {
var resW = $(window).width();
clearTimeout(tOut);
if ( (ww>limit && resW<limit) || (ww<limit && resW>limit) ) {
tOut = setTimeout(refresh, 100);
}
});
And the second code by #gdoron
var width = $(window).width();
$(window).resize(function() {
if (width > 769 && $(window).width() < 769) {
location.reload();
}
else if (width < 769 && $(window).width() > 769) {
location.reload();
}
});​
Going with the second code sample, you can check for the alternate conditions using an or operator.
var prevWidth = $(window).width();
$(window).resize(function() {
var currentWidth = $(window).width();
if (
(prevWidth > 769 && currentWidth < 769)
|| (prevWidth > 300 currentWidth < 300)
|| (prevWidth > 1024 currentWidth < 1024)
)
{
location.reload();
}
});​

Adding Media Queries to Javascript

I've got a sticky sidebar going on with this code. But I only want it to affect the .fake-sidebar div when at 768px or below. Could anyone explain how to add media queries to my javascript?
var sticky_offset;
$(document).ready(function() {
var original_position_offset = $('.fake-sidebar').offset();
sticky_offset = original_position_offset.top;
$('.fake-sidebar').css('position', 'fixed');
});
$(window).scroll(function () {
var sticky_height = $('.fake-sidebar').outerHeight();
var where_scroll = $(window).scrollTop();
var window_height = $(window).height();
if((where_scroll + window_height) > sticky_offset) {
$('.fake-sidebar').css('position', 'relative');
}
if((where_scroll + window_height) < (sticky_offset + sticky_height)) {
$('.fake-sidebar').css('position', 'fixed');
}
});
Any help is appreciated. Thanks in advance!
You can add the event on window resize, or on document ready, depending of what you want:
$(window).resize(function() {
var width = $(window).width();
if (width < 768) {
$('.fake-sidebar').css('position', 'relative');
}
else {
$('.fake-sidebar').css('position', 'fixed');
}
});

Categories

Resources