I want to assign different background images to a div depending on the page's address, so for example, if my url is http://www.mywebsite.com/mysubdirectory/ I use the following code:
if(document.URL.indexOf("mysubdirectory") >= 0){
document.getElementById("wrapper").style.backgroundImage = "url('bg-wrapper.jpg')";
}
But it's not working. I even added a bogus document.write command just to make sure the rest of the code was ok and sure enough the bogus line showed up in my browser. Is there something I'm overlooking?
EDIT: Thank you all for your answers - when I use body instead of getElementById("wrapper") in my code, the image shows up, so I doubt it's a path-related issue. I trued adding an onload attribute to the body tag but it's still not working with getElementById. Any ideas?
Your
document.getElementById("wrapper").style.backgroundImage = "url('bg-wrapper.jpg')";
code is correct.
It works fine in this jsfiddle: http://jsfiddle.net/hUuN5/
Are you sure the image is correct. Remember that the path to the file is relative to the location of the current page. NOT the css directory
I'm using Chrome 29.0.1547.66 and none of the anwers worked either.
So I tried:
document.getElementById("wrapper").style.backgroundImage = "url(http://media.nu.nl/m/m1fz6dwa6h3w.jpg)";
It worked taking off the quotation marks from the image url.
Here working as well: http://jsfiddle.net/xEujg/
html css backgroundimage javascript
Try this, I think the image url is wrong most likely. You probably need a relative path of sorts:
document.getElementById("wrapper").style.backgroundImage = "url('/bg-wrapper.jpg')";
Specifying a protocol worked for me in chrome. I couldn't get it to work using the catch all '//'. It had to be 'http://' I'm assuming it must match whatever protocol was used to load the page or iframe.
for example
element.style.backgroundImage="url(http://somedomain.com/images/myimage.jpg)"
or
element.style.backgroundImage="url('http://somedomain.com/images/myimage.jpg')"
worked for me.
If anyone is still interested in this. Here is a solution:
document.getElementById("wrapper").style.background = "url(http://media.nu.nl/m/m1fz6dwa6h3w.jpg)";
This works for me:
var pointer = "url(\'/" + imageArray[imageCounter].toString() + "\')";
document.body.style.backgroundImage = pointer
After spending a bit of time on this, it was the browser's engine parsing the CSS. No good errors in the console.
The solution is to not do everything on the same line.
You have to create a variable, assign it the url and then pass it.
let bg = "url('" + imgUrl + "')";
document.getElementById("wrapper").style.backgroundImage = bg;
Related
I am trying to update a webpage that already has a bit of javascript in it to replace a missing image. The way it works right now is it looks for pcp.gif, and if not found displays an error message image instead. (Just like in this thread)
<p align = center><img src = PCP.gif onerror = "this.onerror=null;this.src='!FireSeasonOnly.gif';">
What I want it to do now is look for pcp.png, if not found display pcp.gif and if BOTH are not found then display the error message image. I'm not having any luck getting the second level to work. I tried wrapping it in an IF but it didn't work the way I was hoping.
<p align = center><img src = pcp.png onerror = "if (this.src='pcp.png') {this.onerror=null;this.src='pcp.gif';} else {this.onerror=null;this.src='!FireSeasonOnly.gif';} ">
The above doesn't work. If the PNG is present, it displays it. If not, it displays the GIF if present. But if both are missing, I get the broken image icon, so it's not hitting my else statement. Any suggestions?
Here's the working answer -- thank you for your help, all, especially floribon!
onerror="this.src=(this.src === location.protocol + '//' + location.host + '/Weather/Maps/pcp.gif') ? '!FireSeasonOnly.gif' : 'pcp.gif';"
I found the answer to my question via a simple Google search, although, there is a slight problem that I ran into.
So far, I have an image on my HTML page with the ID of newAvatar. I am attempting to find this image via its ID, and save it's source into a variable, then eventually into an XML document to be used later on.
When I save this source into a variable, or alert it for checking purposes, it is displaying the full source, which is unusual. For example, I am running my site on a WAMP server, so the variable is saving as:
http://localhost/uploads/newUploadedImage.jpg
When in reality, the source should be plain and simple, uploads/newUploadedImage.jpg
The image tag is
<img src="uploads/newUploadedImage.jpg" width="60px" height="60px;" id="newAvatar"/>
The way i am checking the source is
alert(document.getElementById('newAvatar').src);
Any idea how to get rid of the first lot of junk?
All help is greatly appreciated!
By using #DavidThomas comment before, I managed to get it working. This is what i changed my alert to:
alert(document.getElementById('newAvatar').getAttribute('src'));
var hostname = document.location.hostname;
var url = 'http://' + hostname + '/';
var src = document.getElementById('newAvatar').getAttribute('src'); //'uploads/newUploadedImage.jpg'
var image = src.split('/')[1];
console.log(url);
console.log(image);
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<img src="uploads/newUploadedImage.jpg" width="60px" height="60px;"
id="newAvatar"/>
and
$(function()
{
alert($('#newAvatar').attr('src'));
});
ISSUE: IE version 7 and 8 is not showing updated IMG SRC change done in JavaScript
You can see what I mean if you go to the URL below, and on the left under (3) I want a different liner, you choose one of the swatches; lets say you choose "Asahi Chartreuse". Notice nothing happens to the preview on the left. BUT then if you go ahead and choose another swatch, you will see the preview on the left shift to show Asahi Chartreuse. So it is one behind. This is why I believe it is a "refresh" issue. It works in Chrome just fine.
In IE: Notice if you click on some other control, the refresh happens.
You can see the code here: https://www.casemodo.com/test.asp
WHAT I'VE TRIED SO FAR:
I've tried adding headers to say "no-cache".
I've tried adding "?" and random number after the png file name.
I've tried setting focus() to the image after changing the src.
I've tried, after changing src, telling the style.display to be hidden and then visible.
I've tried creating a hidden (and not hidden) text input box on the page and then setting focus() to it after changing img src.
I've tried setting window.focus().
I've tried (as you see now) setting an alert after changing the src.
GUESS: What it looks like now is the JavaScript engine just pauses after I set that src UNTIL you manually click (focus) somewhere else on the screen. So it never even gets to all of those scripts I've tried above.
Set the src attribute to null, then set it to your new url:
in jquery:
var myImg = $('#myImg');
myImg.attr('src', null);
myImg.attr('src', newUrl);
in straight js:
var myImg = document.getElementById('myImg');
myImg.src = null;
myImg.src = newUrl
This worked for me - it was driving me mad!
Try to use onclick instead of onchange. The latter doesnt work well with some form elements in some browsers.
I've seen similar IE issues solved with a seemingly bizarre reassignment of innerHTML. Suppose "container" is a variable referencing the parentNode of the img. Try "container.innerHTML = container.innerHTML". This triggers a re-rendering and may bring the errant img to life.
Comments on the question:
Please include a code snippet in the question.
Was the javascript in an onchange event, or where?
If the client browser is Google Chrome, does it work?
(Sounds like yet-another-IE-image-src-bug.)
The demonstration page you linked to has been changed since this question was posted;
as I write this, clicking on a swatch causes submit which causes load of a different page.
A suggestion:
Use setTimeout, so that the actual change occurs when the timeout event fires, instead of in the original GUI event thread.
For example, if the original javascript was
SomeFunction();
change this to
setTimeout(SomeFunction, 10);
(where image.src = newURL; is done inside SomeFunction)
This question is probably no longer relevant but we ran into the same issue today when we checked backward compatibility for one of our libraries.
The only thing that worked for us was to replace the image element by itself before changing the value for the src attribute:
var myImg = document.getElementById('myImg');
myImg.parentNode.replaceChild(myImg, myImg);
myImg.src = newUrl;
I was working with a Lazy Loading implementation, and got to a similar problem. For some reason, after changing the data-srcset attributes to srcset in code, even with the other approaches described on this page, the elements still didn't seem to get the new attributes values. After some research, I got to this page on github, about a bug fix on a lazy loading plugin. It gave me the idea to, instead of using the replace option described here, or the your_element.src=null approach, to use something like this:
your_element.setAttribute("src", your_element.getAttribute("data-srcset"));
And it ended up working for me.
I have an iframe to preview some data.
The data is stored in a javascript variable :
var s = '<html><head></head><body>Hello_world</body></html>';
I am passing the data [passing s] to the iframe SRC attribute via Javascript.
Here is the code :
document.getElementById('output_iframe1').src = "data:text/html;charset=utf-8," + escape(s);
So the data is loaded on the iframe except <a> elements.
The Problem is I can see text but not links. However, the element events are working fine(click,hover etc).
I inspected through Firebug and all are working well there.
I changed the HREF attribute to http://somesite/file.html on Firebug and amazingly it worked, but not with #.
Actually what i am doing wrong ??
Why i cant see LINKS without http:// ?
Thank you .
Update 1 : I tested it with latest Firefox 8.0 and it works well,also checked with Google Chrome [Works well,but clicking on any links disappearing all the links],Yeah as usual IE failed in all cases,it looks like IE doesn't know what is an Iframe
Use href="javascript:void(0)" instead of href="#".
OR
Since you are assigning it to a src attribute, you need to encode the string before you apply it. This is because, usually src value is url and "#" is used in browsers url sometimes. Hope you understand what I am saying.
Use encodeURIComponent() or encodeURI(). See the syntax here
http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp
Try This
var s = "<html><head></head><body><a href='#'>Hello_world</a></body></html>";
Instead of This
var s = "<html><head></head><body>Hello_world</body></html>";
My markup is a simple div element with id 'load'. Using jQuery I then load a list of image elements into this div:
$('#load').load('images.html', { }, function() {
$(this).onImagesLoad({
selectorCallback: function() {
....do something....
}
});
});
where images.html is a list like this:
<img src='1.jpg' caption='img 1'>
<img src='2.jpg' caption='img 2'>
...
To ensure that all images are loaded completely, I use the onImagesLoad plugin. This, so far, works just fine on all browsers.
However, on IE8 (and I assume other versions of IE also) when I then iterate over the img elements, I am unable to determine the width/height of the images loaded. The image.context.naturalWidth and naturalHeight attributes don't seem to work.
How do I get a hold of the images' dimension?
Thanks heaps :)
Update
#Simon: That didn't work on IE, and broke the other browsers as well.
#Jenechka: If "imageDomElement" is just another name for the "image" variable in my example above, then it doesn't work. Or what do you mean by that DomElement?
If you haven't resized the image, you could use:
image.width()
and
image.height()
It's been a while but I finally found some time to tinker with this again. The above problems are still there, but here is what I think is going on.
When I load the initial images then yes, the file is loaded and image objects are generated. But it seems that the attributes are not correct yet, and they won't be until the image is actually added to the DOM of the site and rendered. A div/image on hide() on IE has no dimension information whatsoever, on Safari there is some information available. For example, without adding the following div anywhere
var test = $("<div><img src='test.jpg'></div>")
the image contained there has the following information:
width() = 0,
attr("width") = 600,
css("width") = "", and
img[0].clientWidth = 0.
That's on Safari; on IE it's the same except attr("width") = 0 and css("width") = "auto". Now I can't use this, and that's what broke my script and why I posted my initial question. However, the moment I append this div and have it rendered, all the correct values show up in the image object.
I'm writing a little gallery thinghie, which shows whatever images I have in that second .html file that I load; that gallery, however, computes and places the thumbnails, and prepares the images it shows in full resolution. To make this look ok, I basically wanted to create the entire thing hidden, and then fade it in. Alas, it seems that this whole idea won't pan out. A friend suggested to load everything into a tiny iframe off to the left where it's not visible, and work with that. Perhaps that's the way to go.
Another thing I noticed, and that seems to be very closely related to the aforementioned load issue is clone(). It seems that if an image is rendered, a
var newimg = img.clone()
generates the same "empty" image object that I have to deal above. Even when the original image is visible and contains all the right attributes, its clone does not.
Right now I don't see any other way than to rethink and rewrite parts of my gallery.
This is quite similar to the other answers, but I have tested it in IE7, so it might be closer to what you want:
$(document).onImagesLoad({
selectorCallback: function() {
$('img').each(function(){
alert($(this).width()+', '+$(this).height());
});
}
});
See here, this may not be exactly how you were using it, but I'm not familiar with this onImagesLoad thing.
imageDomElement.width
imageDomElement.height
or try
imageDomElement.clientWidth
imageDomElement.clientHeight
If you play with jquery, then image.attr(width) should do the trick
But why not using the document.ready instead, could give you less headeache. .
Use the following code instead
$(document).onImagesLoad({
selectorCallback: function() {
$('img').each(function(){
alert($(this)[0].clientWidth +', '+$(this)[0].clientHeight);
});
}
});
What about?
$("#load img").each(function() {
var img = new Image();
img.src = this.src;
alert(img.height + " x " + img.width);
});