jquery window on load and resize not running - javascript

I have this code that is used for a responsive image slider that shows the logos of partners.
This is how it looks.
https://i.scrny.me/yaOn.gif
At times, it randomly stops working, i refresh the page a few times and its working again so I am not sure what the problem is. This is how it looks when it stops working.
https://i.scrny.me/ot1N.png
This is the JavaScript code I am using for this.
$(function() {
var partnerSlider = $('.partners'),
partners = partnerSlider.children().length,
width, partnerHeight, containerWidth, windowSize, columns = 4;
//Making it responsive and all
$(window).on("load resize", function(){
containerWidth = $('.container').width();
windowSize = $(window).width();
if (windowSize >= 992) {
columns = 4;
}
else if (windowSize >= 768 && windowSize < 992) {
columns = 3;
}
else if (windowSize < 768) {
columns = 2;
}
$('#partners').css('width', containerWidth);
$('.partner').css('width', containerWidth / columns);
width = containerWidth / columns;
partnerHeight = $('.partner > img').height() + 20;
partnerSlider.css({width: (partners * width), height: partnerHeight});
});
var rotating = true;
var sliderSpeed = 4000;
var seePartners = setInterval(slidePartners, sliderSpeed);
$(document).on({
mouseenter: function () {
rotating = false;
},
mouseleave: function () {
rotating = true;
}
}, '.partners');
function slidePartners() {
if (rotating !== false) {
var first = $('.partner:first');
first.animate({'margin-left': '-' + width + 'px'}, 1000, function () {
first.remove().css({'margin-left': '0px'});
$('.partner:last').after(first);
});
}
}
});
As far as I managed to figure out the problem is from this part.
$(window).on("load resize", function(){
containerWidth = $('.container').width();
windowSize = $(window).width();
if (windowSize >= 992) {
columns = 4;
}
else if (windowSize >= 768 && windowSize < 992) {
columns = 3;
}
else if (windowSize < 768) {
columns = 2;
}
$('#partners').css('width', containerWidth);
$('.partner').css('width', containerWidth / columns);
width = containerWidth / columns;
partnerHeight = $('.partner > img').height() + 20;
partnerSlider.css({width: (partners * width), height: partnerHeight});
});
The function is meant to run whenever the page is loaded or resized I believe but sometimes when the page is loaded it doesn't run so it does not automatically assign the sizes for the images and the container.
This is the HTML
<div class="container wow fadeIn" style="overflow:hidden;">
<h2>Partners</h2>
<div class="partners">
<div class="partner">
<img src="assets/images/sponsor.png" class="img-responsive"/>
</div>
<div class="partner">
<img src="assets/images/sponsor.png" class="img-responsive"/>
</div>
<div class="partner">
<img src="assets/images/sponsor.png" class="img-responsive"/>
</div>
<div class="partner">
<img src="assets/images/sponsor.png" class="img-responsive"/>
</div>
<div class="partner">
<img src="assets/images/sponsor.png" class="img-responsive"/>
</div>
<div class="partner">
<img src="assets/images/sponsor.png" class="img-responsive"/>
</div>
<div class="partner">
<img src="assets/images/sponsor.png" class="img-responsive"/>
</div>
</div>
</div>
Any help will be appreciated.

I believe the issue with your code is related to the version of jQuery you have. Sometime within the jQuery 3.x.x version (not sure when exactly) changes were made to make the on ready event handlers run asynchronously. This means there can be scenarios where the on load event completes before the ready event is fired. In you case, this becomes an issue because if the load event has been fired before ready is called, the window.load event handlers registered inside jQuery's document.ready() will not run. This sequence can depend on many things like how quickly the page loads, image caching..., which is why you see the issue occurring inconsistently.
The solution is to update the code you have and move the $(window).('on') event handler outside the docuemnt.ready function: $(function(){}). Additionally, since I didn't see it in the jsFiddle you provided, make sure the scripts for your js code are embedded withing the <body> element, as this is the ideal place to put code that impacts the rendering of the page.
I've update teh jsfiddle provided to include these changes, take a look:
Updated jsFiddle

Related

Remove Class from all images on browser resize

I have no idea from javascript and I need a little help here. From resources here and there I am trying to do the following logic.
When the browser has a width less than 700px then all images that have class "star-wars" will have that class removed.
$(window).resize(function() {
/*If browser resized, check width again */
if ($(window).width() < 700) {
function myFunction() {
var element = document.querySelectorAll('img.has-zoom');
element.classList.remove("has-zoom");
}
}
});
Obviously the above code is wrong. I need you to tell me how the above can be written correctly (if this is the right one).
The document.querySelectorAll('img.has-zoom') will return a NodeList not an element.
You need to loop through the returned list or get the element you want from it to extract the classList from it.
Try :
window.addEventListener('resize', removeClass);
function removeClass() {
width = window.innerWidth || $(window).width();
if ( window.innerWidth < 700) {
var elements = document.querySelectorAll('img.has-zoom');
[].forEach.call(elements, function(el) {
el.classList.remove("has-zoom");
});
}
}
Sample that removes class after 2 seconds:
setTimeout(function() {
var elements = document.querySelectorAll('img.has-zoom');
[].forEach.call(elements, function(el) {
el.classList.remove("has-zoom");
});
}, 2000);
.has-zoom {
border: 3px solid yellow;
}
<img alt="Image 1" src="https://www.gravatar.com/avatar/a29d596b0af040d7def18d1801340a8b" class="has-zoom">
<img alt="Image 2" src="https://www.gravatar.com/avatar/a29d596b0af040d7def18d1801340a8b">
<img alt="Image 3" src="https://www.gravatar.com/avatar/a29d596b0af040d7def18d1801340a8b" class="has-zoom">
Since you are already using jQuery, here is a simple solution:
$(window).resize(function() {
if ($(window).width() < 700) {
$(".has-zoom").removeClass("has-zoom")
}
});
Your code is almost correct.
You can add an event listener to the window to check if it is being resized, and from there check the actual size of the screen and remove the classes where necessary.
<!-- images with class -->
<img class="star-wars" />
<img class="star-wars" />
<img class="star-wars" />
<img class="star-wars" />
<img class="star-wars" />
// javascript
// listen for the window being resized
window.addEventListener('resize', checkScreenSize);
// function to call every time the window is resized
function checkScreenSize() {
// check size of window
if ( window.innerWidth < 700) {
// loop through images with class name attached
var images = document.getElementsByClassName('star-wars');
for ( var i = 0; i < images.length; i++ ) {
// remove class from each image
images[i].classList.remove('star-wars')
}
}
}
You can add another conditional statement to add the class back on if the window gets resized above 700px again.
var classNameRemoved = false;
$(window).resize(function () {
if ($(window).width() < 700 && !classNameRemoved) {
var elements = document.querySelectorAll("img.has-zoom");
elements.forEach(function (element) {
element.classList.remove("has-zoom");
});
classNameRemoved = true;
}
});
As you said, below code will remove the elements which has class 'star-wars' when the browser width is less than 700px
$(document).ready(function(){
$(window).resize(function(){
if ($(window).width() < 700) {
const element = document.querySelectorAll('img.has-zoom');
if (element.classList.contains("classToBeRemoved")) {
element.classList.remove("classToBeRemoved");
}
}
});
});

Change img src with another img attribute on Responsive

I created a attribute for img tag as in the example code like data-tablet, data-mobil
<div class="myDiv">
<img src="img-1.jpg" data-tablet="img-2.jpg" data-mobil="img-3.jpg">
</div>
and I want if my screen change for tablet my img src change with data-tablet or my screen is for mobil my src must change with data-mobil
MY JS
$(document).ready(function(){
$(window).resize(function(){
var tabletSrc = $(".main-carousel img").attr("data-tablet");
var mobilSrc = $(".main-carousel img").attr("data-mobil");
if($(window).width() <=768){
$('img').attr('src',tabletSrc);
}
if($(window).width() <=480 ) {
$('img').attr('src',mobilSrc);
}
});
});
click to see my works
question is how can I do that I want if u click you gonna see nothing work
note: I don't want to use srcset or css
Please see this CodePen for a working version.
There were some issues with your code:
Both the case for mobile and tablet was executed in the mobile case.
$(".main-carousel img") is a collection of images. Instead of that, you probably want to operate on a single image. This can be done with the help of .each().
Here is the relevant code:
$(window).resize(function() {
if ($(window).width() <= 480) {
$('img').each(function() {
$(this).attr('src', $(this).attr('data-mobil'));
});
} else if ($(window).width() <= 768) {
$('img').each(function() {
$(this).attr('src', $(this).attr('data-tablet'));
});
}
});
Use srcset instead of js based validations for device dimensions.
<img src="images/space-needle.jpg"
srcset="images/space-needle.jpg 200w, images/space-needle-2x.jpg 400w,
images/space-needle-hd.jpg 600w">
So, now the browser will automatically device which image to download and show depending on the browser dimensions.
Check out more
https://www.sitepoint.com/how-to-build-responsive-images-with-srcset/
You can try this for you carousel multiple images
function makeResize(){
var imageSrc = $(".myDiv img");
if($(window).width() <=768 && $(window).width()>480){
$(imageSrc).each(function(key,value){
$(value).attr('src',$(value).data('tablet'));
});
}else if($(window).width() <=480 ) {
$(imageSrc).each(function(key,value){
$(value).attr('src',$(value).data('mobile'));
});
}else{
$(imageSrc).each(function(key,value){
$(value).attr('src',$(value).data('default'));
});
}
}
$(document).ready(function(){
$(window).resize(function(){
makeResize();
});
makeResize();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myDiv">
<img src="org1.jpg" data-default="org1.jpg" data-tablet="tablet1.png" data-mobile="mobile1.jpg">
<img src="org2.jpg" data-default="org2.jpg" data-tablet="tablet2.png" data-mobile="mobile2.jpg">
<img src="org3.jpg" data-default="org3.jpg" data-tablet="tablet3.png" data-mobile="mobile3.jpg">
</div>
Note Copy and add proper image source then try. Above code will work for multiple images.
You are using wrong class name. Your div has class "myDiv" and you are selecting by "main-carousel"
$(document).ready(function(){
$(window).resize(function(){
var tabletSrc = $(".myDiv img").attr("data-tablet");
var mobilSrc = $(".myDiv img").attr("data-mobil");
if($(window).width() <=768){
$('img').attr('src',tabletSrc);
}
if($(window).width() <=480 ) {
$('img').attr('src',mobilSrc);
}
});
});
Here is codepen
Keep the short width first. Your validation always goes for tablet first. since 480 < 768
Change your conditions like this.
$(window).resize(function(){
var tabletSrc = $(".someDiv img").attr("data-tablet");
var mobilSrc = $(".someDiv img").attr("data-mobil");
var imgSrc = "defaultImageSrc" //src for default image
var windowWidth = $(window).width();
if(windowWidth <= 480 ) { //first small width
imgSrc = mobilSrc;
}else if(windowWidth <= 768){ //next larger one
imgSrc = tabletSrc;
} //if else default will there for you which is initialised there.
});
Try this:
$(window).resize(function(){
var realImg = $(".main-carousel img").attr();
var tabletSrc = $(".main-carousel img").data("tablet"); //use .data instead of attr
var mobilSrc = $(".main-carousel img").data("mobil");
if($(this).width() <= 768){
$('img').attr('src',tabletSrc);
}
else if($(this).width() <= 480 ) { // use else if instead of if
$('img').attr('src',mobilSrc);
}
else{
$('img').attr('src',realImg);
}
});

Jquery swap divs on resize

so I have got a small issue with the website I am working on.
I have a popUp div that is created dynamically and popUp windows needs to be responsive, so the problem is that I want to swap 2 divs inside that popUp when the width of window is lower than 768px.
I am not gonna pollute with my massive code but will simplify it.
(function($) {
function resize() {
var $window = $(window);
if ($window.width() < 768) {
add/remove classes
}
}
function viewEvent {
$("div.main_view").prepend("<div class='row popUp' id='popUp' style='max-width:700px; margin-right:5px;'></div>");
$popUp.append("<div class='inner_boxed col-xs-12 col-sm-7 col-md-7 col-lg-7' id='inner'></div>");
var $text = $("div#text");
$text.append(lorem);
var $img = ("<div class='col-xs-12 col-sm-5 col-md-5 col-lg-5' id='img' style='margin-top: 1.5rem; min-height: 250px;'><img src='img/train_deal.jpg'></div>");
$popUp.append($img);
resize();
}
viewEvent();
$window
.resize(resize)
.trigger('resize');
})(jQuery);
So at the moment, I get image after text.
So when the width reaches 768 and lower, I want my image appear before text and when width reaches 768 and higher I want it all back.
to swap two elements next to each other you can use .insertBefore() or/and .insertAfter() something like this
$(document).ready(function(){
$(window).on('resize' , function(){
resize('#div1' , '#div2');
});
});
function resize(el1 , el2){
var $window = $(window);
if($window.width() <= 400){
$(el2).insertBefore(el1);
}else{
$(el2).insertAfter(el1);
}
}
Working Example

could not change image dynamically

I'm trying to change image dynamically for my responsive site. When i resize my browser, nothing happens. Is there anything wrong with my code?
<script type = "text/javascript">
$(window).ready(function() {
var wi = $(window).width();
$(window).resize(function() {
var wi = $(window).width();
if (wi <= 480){
document.getElementsByClassName('party')[0].src="images/1.jpg"
}
else {
document.getElementsByClassName('party')[0].src="images/5.jpg"
}
});
});
My html as follows:
<div class="party">
<div class="dance">
<h2 id="head">Your Party begins here</h2>
<p id="intro1">Start dancing</p>
<a id="starter" href="#" >Dance now</a> </div>
<a id="main" href="#"><img class="img-responsive" src="images/default.jpg" alt="main image"></a>
Image element have class img-responsive and not party. also you are mixing javascript and jquery. i would rather suggest you to either use pure JS or jquery:
$(window).resize(function() {
var wi = $(window).width();
$('.img-responsive').attr('src',wi < = 480 ? "images/1.jpg" : "images/5.jpg");
});
$(window).ready(function() {
$(window).resize(function() {
var wi = $(window).width();
if (wi <= 480){
$("#main").find("img").attr("src","images/1.jpg")
}
else {
$("#main").find("img").attr("src","images/5.jpg");
}
});
});
Try this code,also you were unnecessarily declaring wi twice.
Just as Milind Anantwar suggests, you are attempting to set the src of the div with the "party" class. You should instead be setting the image with the class "img-responsive"'s src-attribute.
Try the plunkr below, and check the logs in the console which shows that you are in fact grabbing the wrong element in your jQuery code.
if (wi <= 480) {
var partyElement = document.getElementsByClassName('party')[0];
console.log(partyElement);
document.getElementsByClassName('img-responsive')[0].src = "images/1.jpg"
} else {
var partyElement2 = document.getElementsByClassName('party')[0];
console.log(partyElement2)
document.getElementsByClassName('img-responsive')[0].src = "images/5.jpg"
}
Heres a plunkr
http://plnkr.co/edit/wBVt4qQZdOOrw94rHJFZ?p=preview

Tumblr jQuery - code not executing (NOT Masonry / Infinite scroll)

So, I was helping a friend develop a theme for her tumblr. As every reasonable web dev would do, I first developed it locally on my harddrive, putting in filler images. On my local copy, everything works fine. When I port it to a tumblr theme, a portion of the jQuery code ceases to function.
I'm using jQuery 2.0.3, and have MixItUp working, and a lightbox-esque function I wrote.
Here's the bit in question:
jQuery/javascript
$(window).load(function() {
$('.mix').on('click', function() {
var source = $(this).find('img').attr('src');
var image = $('<img src='+source+'>');
$('.overlay').children().remove();
$('.overlay').append(image);
$('.overlay').find('img').load(function() {
var overlayWidth = $('.overlay').width();
var overlayHeight = $('.overlay').height();
var overlayWPadding = overlayWidth - 40;
var imageWidth = $('.overlay').find('img').width();
var imageHeight = $('.overlay').find('img').height();
if (imageWidth > overlayWidth) {
var ratio = imageWidth / imageHeight;
var adjustedHeight = overlayWPadding / ratio;
var marginValue = (overlayHeight - adjustedHeight) / 2;
var marginTop = marginValue + "px";
$('.overlay').find('img').width(overlayWPadding);
$('.overlay').find('img').height(adjustedHeight);
$('.overlay').find('img').css('margin', ''+marginTop+' auto');
}
});
$('.overlay').css({'left': '200px', 'display': 'none'}).fadeIn(1000);
});
$('.overlay').on('click', function() {
$(this).fadeOut(500);
});
});
The HTML it affects:
<div id="Grid">
<div class="mix">
<img src="img/02.jpg" />
</div>
...
</div>
The respective tumblr code for it:
<div id="Grid">
{block:Posts}
<div class="mix" id="{PostID}">
{block:Photo}
<img src="{PhotoURL-HighRes}" />
{/block:Photo}
</div>
{/block:Posts}
</div>
The problem is that the function doesn't add the .overlay div when an image is clicked. Like I said, this works fine when I coded it locally, but when I load this into tumblr, it doesn't work. What's wrong and how do I fix it?
I don't think the CSS is the problem, but I'll put up any requested CSS.
Edit:
The issue is because there is no div like <div class="overlay"></div> in the given Tumblr page.
The lightbox is working fine when I added the below code.
<div class="overlay"></div>
Try use createElement() or appendTo() a div.overlay right after declare var image.

Categories