Change img src with another img attribute on Responsive - javascript

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

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

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

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

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

Toggling text of "a href" based on screen width

Using jQuery/jQueryMobile, I have a link as follows:
<a href="index.html" id="HomeLink" data-role="button" data-mini="true" data-icon="home" data-iconpos="top" >Home</a>
I am trying to test various screen sizes, and if the screen width is less than 300px, I want to change:
data-iconpos="top"
to
data-iconpos="notext"
so I only get the icon. I have tried to do it with JavaScript:
var hl = document.querySelector('#HomeLink');
if ($(window).width() < 300) {
hl.setAttribute("data-iconpos", "notext");
} else {
hl.setAttribute("data-iconpos", "top");
}
But it won't work.
Question: can it be done in CSS instead.
If not: how can it be done in JavaScript?
You can't really set a data attribute with CSS as far as I know, but since you're already using jQuery, why not try it all the way :
$('#HomeLink').data('iconpos', ($(window).width() < 300 ? 'notext' : 'top') );
Remember to wrap that in document ready!
You can do this way altering your code:
var hl = $('#HomeLink');
if ($(window).width() < 300) {
hl.data("iconpos", "notext");
} else {
hl.data("iconpos", "top");
}
with .attr():
var hl = $('#HomeLink');
if ($(window).width() < 300) {
hl.attr("data-iconpos", "notext");
} else {
hl.data("data-iconpos", "top");
}
Try to wrap the code in window resize event, eg:
$(window).resize(function () {
check();
})
$(function () {
check();
})
function check() {
if ($(window).width() < 300) {
$('#HomeLink').attr('data-iconpos', 'notext');
} else {
$('#HomeLink').attr('data-iconpos', 'top');
}
}
I would like to suggest using a different approach.
The data-iconpos="top" looks a bit out of place to me here. I have a feeling (perhaps I'm wrong) that you're attempting to inline your styling into the HTML.
Why not try media queries?
#media screen and (max-width: 300px) {
#HomeLink {
/* styling for HomeLink when screen width is less than 300px */
}
}
This is a CSS-only solution. It works if the user decides to resize the screen after the page has loaded. Try resizing the "Result" frame in this jsfiddle and notice the color of the link changing.
Suggested reading:
http://alistapart.com/article/responsive-web-design
https://developer.mozilla.org/en-US/docs/CSS/Media_queries
And here are the docs on media queries: http://www.w3.org/TR/css3-mediaqueries/
Warning: mind ahem, IE below 9, ahem...

Categories