could not change image dynamically - javascript

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

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

jquery window on load and resize not running

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

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

changing part of src name with jquery, keeps repeating when window resized

I have code written to find the src of all images inside a particular div and change the src name when the window is less than 900 wide. It works fine upon page refresh, but when I resize the window it continuously runs the code and I get this error
GET
file://macintosh%20hd/Users/jessicamele/Desktop/tom%20mendicino/images/boys3_small_small_small_small.jpg
net::ERR_FILE_NOT_FOUND
It just keeps adding the "_small" over and over again. Here is my code:
<div class="threePicsBoys group">
<img src="images/boys3.jpg" alt="street signs" class="boysPics1">
<img src="images/boys2.jpg" alt="city house" class="boysPics2">
<img src="images/boys1.jpg" alt="2 boys" class="boysPics1">
<img src="images/boys4.jpg" alt="philly signs" class="boysPics2">
<img src="images/boys5.jpg" alt="religious statue" class="boysPics1">
</div>
$(function() {
if (windowWidth <= 900) {
var img = $(".threePicsBoys.group").find("img").map(function() {
var src = $(this).attr("src");
var newName = src.replace(".jpg","_small.jpg");
$(this).attr("src",newName);
});
}
});
}
I could really use some help.
This script will check if the window is so thin that it has to change the src, but will also revert the changes when it have become wider than 900.
I slightly changed the mechanics to make it work. windowWidth, for example, wasn't a declared variable, and the rest didn't seem to do that much either.
var thinWindow = false;
$(window).on('load resize', function(){
if($(window).width() <= 900){
if(!thinWindow){
$('.threePicsBoys.group img').each(function(){
var src = $(this).attr("src");
var newSrc = src.replace(".jpg","_small.jpg");
$(this).attr("src", newSrc);
})
thinWindow = true
}
}else{
if(thinWindow){
$('.threePicsBoys.group img').each(function(){
var src = $(this).attr("src");
var newSrc = src.replace("_small.jpg",".jpg");
$(this).attr("src", newSrc);
})
thinWindow = false
}
}
})
Hope this helps
This code will loop forever when window is less than 900 width. If you wish to you only run on window change width you must add the correct event binding
$(window).resize(function() {
if (windowWidth <= 900)
{
var img = $(".threePicsBoys.group").find("img")
var src = img.attr("src");
if (!(src.indexOf("_small.jpg") > -1))
{
var newName = src.replace(".jpg","_small.jpg");
img.attr("src",newName);
}
}
});

Change image source folder for mobile version with javascript

Sorry I'm a newbie with JS and I've been having trouble with some JS I found here on stackoverflow. My situation is that I have a div with two images inside, and I want to change the source path of those images when the window is less than 480px. My code is this:
<div id="bigFoto">
<img src="img/photo1.jpg" alt="text for alt" id="photo1">
<img src="img/photo2.jpg" alt="text for alt" id="photo2">
</div>
And The current script I'm running is:
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img#photo1").attr("src","img/mobile/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/mobile/photo2.jpg");
}
else{
$("#bigFoto img#photo1").attr("src","img/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/photo2.jpg");
}
});
This script is working right, but now let's say I want that div to have 20 images, my guess is that I would have to add every one of them in this script right?
The real question: is there a way to target all images instead and just add the /mobile part on the source path? ,since the filename remains the same.
Thanks so much for your help!
You can use jQuery's each function to loop through all the elements returned by a query
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/mobile/"+photoName)
})
}
else{
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/"+photoName)
})
}
});

Categories