change img source with attr not working on ios5 - javascript

I'm trying to change the source of an image and have t fade in when you click in another spot, and it's set up like so
$('.thumbs').bind('click', function() {
$('#MyT').attr('class', 'wierd');
$('#MyT').fadeIn(0);
});
it works well when I test it on Chrome, but when I upload it to iPad, it doesn't change the source. What am I doing wrong here?

Changing the class value of the image won't change its src. If you wanted to change its source, you would do something like this:
$(".thumbs").on("click", function(){
$("#MyT").attr("src", "image2.png").fadeIn("slow");
});
I'm assuming of course there is a <img src="foo.png" id="MyT" /> on your page.

Related

Why is my div not updating when changing its class with JavaScript?

I currently have a div that's used to display and image via CSS.
For example:
HTML
<div id="myDiv" class="play"></div>
CSS
.play{background: url('../img/playIcon_black.png') no-repeat;}
This image appears as it should.
What I'm attempted to do is to change the image by changing the class (via JavaScript).
Example:
CSS
.pause{background: url('../img/pauseIcon_black.png') no-repeat;}
JavaScript
function myFunction() {
myDiv.className = "pause";
}
When I call myFunction() everything seems to work correctly with one exception. Occasionally the image does not update in the browser.
A few things to note:
I'm certain the function is being called correctly. If I put a console.log() statement within the function, it prints when it should. Additionally, if I inspect the element within the browser, the class is in fact changed to .pause
The image changes from the "play icon" to blank once the function is called, BUT upon hovering over the div the images then appears permanently.
This only seems to happen once the page is initially loaded. Meaning, I can only recreate the issue once upon refresh, then everything works correctly after that.
I have attempted to clear my cache but nothing seems to have changed.
(I'm not sure how relevant this is) I'm calling myFunction() via onended attribute of an audio tag.
For example:
<audio onended="myFunction()"></audio>
But I'm not certain if this would affect anything because the function appears to be called correctly.
Any ideas of why this might be happening?
So the issue is that when you change the class, the browser has to fetch the new image, which takes time. One way to fix the issue is by using sprites, where both images are actually in one image and you only show a piece of that image at a time.
Another solution is to preload the image and then apply the preloaded image source to your new element like this:
var image = newImage();
image.src = '../img/pauseIcon_black.png';
function myFunction() {
var cssBackground = 'url(' + image.src + ') no-repeat';
myDiv.style.background = cssBackground;
// Optionally with jQuery instead:
// $('#myElementID').css('background', cssBackground);
}
Note that if you call myFunction before the image loads you'll encounter the same error. The difference is that this will load the image when the page is loaded (or more properly, when this JS executes and myFunction is assigned) rather than when myFunction is called. To ensure the image is loaded you can use the onLoad event handler for the image object. For more details on preloading images check out this answer: preload image then change background javascript
You need to get the element id
function myfunction(){
var myDivElem = document.getElementById('myDiv');
myDivElem.className = 'pause';
}
You can use document.getElementById("myDiv").className="";in your function
OK if you don't want use first solution you can use second one:
You can add a class to element using
document.getElementById("myDiv").className +=" n";
Then add a class named .play.n to your css file after class named.play
Then add your image address.
If you want to manipulate the div with id "myDiv". Use it as
document.getElementById('myDiv').class
Sample codesnippet: example snippet

onload not working in <img> element

I don't understand why this function doesn't fire. I want to declare an image in HTML with a single onload function, which will automatically take care of the image's source and mouseover/out functions.
The HTML looks like this:
<img id="menuBtnNovo" onload="imgButton(this)"/>
and the JS function imgButton looks like this:
function imgButton(e){
window.alert("asdasdad");
e.src="images/def/" + e.Id + ".png";
e.onmouseover= function(){ *change image here*}
e.onmouseout= function(){ *change image back here*}
}
Now, not even the alert pops up, and I don't know why. I tried putting script in <head> and setting src to none src="" in the <img>. I'm using Firefox, but it doesn't work in Edge either.
Question is: how do I fire onload function on an image element?
Also, if you have any idea of your own way of implementing this behaviour of automatically loading certain images (that would actually be buttons/links), feel free to share it. I'm new to JS but not to programming.
As you might see, all images are in "images/def/..." and all images for when the mouse is over the img are in "images/mo/...".
I always try and let browser do image replacements, but if you have to use script, than you can do something like this on DOM ready, or window load event:
$('img[data-regular]').each(function(i) {
var thisImage = $(this);
var regular = thisImage.data('regular');
var hover = thisImage.data('hover');
thisImage.attr('src', regular);
/* Preload image for hover */
$('<img/>')[0].src = hover;
/* Set events */
thisImage.on('mouseenter', function(e) {
thisImage.attr('src', hover);
}).on('mouseleave', function(e) {
thisImage.attr('src', regular);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img data-regular="https://placehold.it/350x150" data-hover="https://placehold.it/450x200" />
Also on JSFiddle.

Responsive image with hover effect

I currently have an image with a hover effect that looks like this:
<img src="jb-400x500.jpg" alt="yada" width="400" height="500" onmouseover="this.src='jb-400x500-2.jpg';" onmouseout="this.src='jb-400x500.jpg';" />
This works fine, except I would like for only the second image (jb-400x500-2.jpg) to be displayed for mobile viewers. I tried using srcset to achieve this, but doing so gets rid of the mouseover effect for desktop viewers. Is there any way to make the two work together?
Thanks.
If you include a srcset on a browser that supports it, the src attribute will be ignored. So your script will need to change the srcset as well as, or instead of, the src attribute. E.g.
<img src="jb-400x500.jpg" alt="yada" width="400" height="500"
srcset="jb-400x500-2.jpg 720w,jb-400x500.jpg 1x"
onmouseover="this.setAttribute('srcset','jb-400x500-2.jpg 720w,jb-400x500-2.jpg 1x');"
onmouseout="this.setAttribute('srcset','jb-400x500-2.jpg 720w,jb-400x500.jpg 1x');" />
You may need to add some JavaScript via the <script> tag at the bottom of your HTML document.
For starters, you have to add an id attribute to your image so we can select it.
<img src="jb-400x500.jpg" id="image-1" alt="yada" width="400" height="500" />
Secondly, we'll use Javascript to detect if you're using a touch device, and apply the necessary behaviors to your image element:
<script>
// Detect if browser enables touch events
var isTouchDevice = "ontouchstart" in document.documentElement;
// Select your image
var image1 = document.getElementById("image-1");
if(isTouchDevice){ // If it's touch, change the image src
image1.src = "jb-400x500-2.jpg";
}else{ // If it's not touch, assign mouseover and mouseout events
image1.addEventListener("mouseover", function( event ) {
image1.src = "jb-400x500-2.jpg";
});
image1.addEventListener("mouseout", function( event ) {
image1.src = "jb-400x500.jpg";
});
}
</script>
Remember to add your <script> at the bottom of your document, right before you close </body>.
You need to use css and #media-query to achieve this effect
Basically I can tell that you need to add two images with different hover effects – one for desktop and one for mobile
And hide one of them depending on screen resolution with css.

Using JavaScript to dynamically change display style in img tags

I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.
image(s) links:
<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">
My JavaScript:
function imgError()
{
alert('The image could not be loaded.');
var _aryElm=document.getElementsByTagName('img'); //return an array with every <img> of the page
for( x in _aryElm) {
_elm=_aryElm[x];
_elm.className="photo240off";
}
}
The style photo240off equals to display:none.
Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.
(the overall script works well, because I get the alert).
Use this to get the image with the error.
Change to:
onerror="imgError(this)"
Then the function can be:
function imgError(el) {
alert('The image could not be loaded.');
el.className = "photo240off";
}
You need to reference the image from your onerror call and change the class only for that one.
Something like this:
HTML
<img class="photo240" src="example.jpg" onerror="imgError(this)">
JS
function imgError(el) {
el.className="photo240off";
}

Javascript replace( ) function running more than once on the same image

I'm running a Javascript replace function to replace standard images with class="replace-2x"on my jQuery Mobile site with Retina-quality images if the user is on a mobile device with Retina display. For example, on a Retina device, logo.png will be replaced with logo#2x.png. The JS function is here:
function highdpi_init() {
$(".replace-2x").each(function () {
var src = $(this).attr("src");
$(this).attr("src", src.replace(".png", "#2x.png").replace(".jpg", "#2x.jpg"));
});
}
$(".page").live('pageinit',function(event){
highdpi_init();
});
I'm now running into an issue where the replace function is running more than once. So for example, it replaces logo.png with logo#2x.png as the page is loading, but then as the page continues to load, it KEEPS replacing .png with #2x.png in the img src over and over so that the image tag ends up looking like this:
<img src="mobile/images/logo#2x#2x#2x#2x#2x#2x#2x#2x#2x#2x#2x.png" class="replace-2x" alt="logo" width="200">
How can I prevent this from replacing on a single img element more than once? Keep in mind, I will have multiple images on the same page, so the function will need to apply to all images, but only one time each.
The problem is surely that your 'pageinit' event is being called more than once. You can either follow MДΓΓ БДLL's idea (which won't work if images are dynamically added) or you can make your handler smarter so that it doesn't replace the src if it already was replaced
function highdpi_init() {
$(".replace-2x").each(function () {
var $this = $(this);
var src = $this.attr("src");
$this.attr("src", src.replace(".png", "#2x.png").replace(".jpg", "#2x.jpg"));
// Remove the class so it doesn't replace it again
$this.removeClass('replace-2x')
});
}
You don't need JS for this, you could do it in CSS only.
<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" href="/css/highdpi.css"/>
You could make your images look like
<img src="transparent.gif" class="logo-a" alt="logo" width="200" />
And in highdpi.css you could do
img.logo-a {
background-image: url('file#2x.png')
}
And in lowdpi.css
img.logo-a {
background-image: url('file.png')
}
Using .one() should work since it is just a binding and if you are using Jquery Mobile the way that is suggested it will be just fine. That is unless you are passing back the html from the server. In which case it would be a good idea to add an extra condition to make sure that the src doesn't already have #2x.png before replacing.
There is disappointingly little documentation on pageinit on the offical jQuery Mobile docs. So I'm going to speculate here. It looks like pageinit is used to fire events for when a specific DOM element has finished loading, since it may not have been loaded on the initial page load (deferred until needed). That being said, it may be that adding/altering images to the DOM element in question fires the pageinit again. Could you tag each updated image with something that says, 'hey, I've already been updated to 2x'? Something such as
$.data(targetimg, 'retinafied', true);
And then check for that value before replacing the src?

Categories

Resources