I'm dynamically creating an image via javascript like this:
var dragimg = null;
function createImage(g) {
dragimg = document.createElement("img");
dragimg.src = "link/to/image.png";
dragimg.style.width = "50px";
dragimg.style.position = "absolute";
dragimg.style.zIndex = 100;
$("body").prepend(dragimg);
}
After creating the Image, I want to remove it at some point by calling this function:
function removeImage() {
dragimg.remove();
}
This works well in Chrome, Firefox & Opera. However, it doesn't work in Internet Explorer 11.
I'd also like to point out I have an document.onmousemove function set which manipulates the left and top attribute of the created image when the mouse moves. This works well in all browsers - but I'm not sure if it has something to do with the remove-problem.
I've also tried to remove the image by dragimg.parentNode.removeChild(dragimg), but same result.
A few things other than the classic just-use-jquery answer:
element.remove() is not supported yet by Internet Explorer, according to the API: http://msdn.microsoft.com/en-us/library/ie/hh772117(v=vs.85).aspx. It's an experimental technology: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode.remove
Are you sure parentNode.removeChild isn't working because it is for me: http://jsfiddle.net/limdauto/wztm1dgk/
Before
After
To use jQuery remove method you need this:
function removeImage() {
$(dragimg).remove();
}
Your dragimg is a dom element, but $(dragimg) is a jQuery element. While jQuery prepend method accepts dom elements, remove does not - it applies to jQuery element itself or to selector. More about jQuery remove and prepend.
I'm not sure the context where you are calling the removeImage function, but the code below demonstrates inserting the image element and removes it after an interval of 2 seconds.
Note: Replace the path to your image.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var dragimg = null;
function createImage(g) {
dragimg = document.createElement("img");
dragimg.src = "someimage.jpg";
dragimg.style.width = "50px";
dragimg.style.position = "absolute";
dragimg.style.zIndex = 100;
$("body").prepend(dragimg);
}
function removeImg() {
dragimg.parentNode.removeChild(dragimg);
}
createImage(null);
window.setInterval(removeImg, 2000);
</script>
</body>
</html>
Related
Look at the following html code of the web page:
<!DOCTYPE html>
<html><head><script>
function hide()
{
var e = document.getElementById('test');
e.style.transition = 'visibility 0s,opacity 0s';
e.style.visibility = 'hidden';
e.style.opacity = '0';
e.style.transition = 'visibility 5s,opacity 5s';
show();
}
function show()
{
var e = document.getElementById('test');
e.style.visibility = 'visible';
e.style.opacity = '1';
}
</script></head><body>
<div id="test">Test</div>
<button type="button" onclick="hide()">go!</button>
</body></html>
If you open this html file in any standard browser (I tested in on Mozilla Firefox and Opera, under Windows 7) and click the button, nothing will happen (the text 'Test' will not vanish!).
I'm guessing that this is a matter of a kind of 'intelligence' of the browser. So, my question is: is it possible (for the above html code) to force the browser to hide the element?
You should not perform multiple changes to the same style property at once (transition and opacity in your case), as only the last values assigned to those properties will actually get an effect. The other value(s) are not processed by the browser -- that only happens when you give control back to the browser.
So only set the opacity to one value, the transition to one value, and then give control back.
Use setTimeout for this: it gives control back to the browser who will call you back when a certain time has elapsed.
function hide() {
var e = document.getElementById('test');
e.style.transition = 'opacity 0s';
e.style.opacity = 0;
setTimeout(showSlowly, 100); // This gives the browser time to perform the hiding action
}
function showSlowly() {
var e = document.getElementById('test');
e.style.transition = 'opacity 2s';
e.style.opacity = 1;
}
<div id="test">Test</div>
<button type="button" onclick="hide()">go!</button>
Read about Mutation Observers and how to react to specific DOM changes elegantly.
https://developer.mozilla.org/es/docs/Web/API/MutationObserver
Basically, you instantiate the MutationObserver object, setup the listeners and define the code to be run when a certain change in DOM appears.
This has gotten so far,that I will sum up what we found out:
Inside the event handler the attribute src cannot be read in IE8 (FF works fine), neither with jQuery nor with usual javascript
The only way to get the data was to get it outside the handler, write it to an array and read it afterwards from the inside of the handler
But there was still no possibility to write to src (neither jQuery nor javascript worked - only for IE 8)
I've got it working by writing the img elemts themselves to the document, but the reason behind this problem is no solved
The snippet we have is used twice.
The old code
<script type="text/javascript">
jQuery(document).ready(function() {
//...
//view entry
jQuery('.blogentry').live('click',function(){
// Get contents
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
imgleft = jQuery(this).children('.Image_left').attr('src');
imgcenter = jQuery(this).children('.Image_center').attr('src');
imgright = jQuery(this).children('.Image_right').attr('src');
// Write contents
jQuery('#bild_left').attr('src', imgleft);
jQuery('#bild_center').attr('src', imgcenter);
jQuery('#bild_right').attr('src', imgright);
jQuery('.person').attr('src', profileimage);
jQuery('#g_fb_name').html(blogauthor);
jQuery('#g_titel').html(blogtitle);
jQuery('#g_text').html(blogtext);
//...
});
//...
// Change entry
jQuery('.blogentry').each(function(){
entryindex = jQuery(this).attr('rel');
if (entry == entryindex)
{
// The following works fine (so 'children' works fine):
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
// This does not work - only in IE 8, works in Firefox
imgleft = jQuery(this).children('.Image_left').attr('src');
imgcenter = jQuery(this).children('.Image_center').attr('src');
imgright = jQuery(this).children('.Image_right').attr('src');
//alert: 'undefined'
alert(jQuery(this).children('.Image_center').attr('src'));
//...
}
}
//...
});
</script>
The new code
Please see my own posted answer for the new code.
UPDATE:
This does not work if called inside of the click event!!!
jQuery('.Image_left').each(function(){
alert(jQuery(this).attr('src'));
});
SOLUTION TO GET THE IMAGE DATA:
relcounter = 1;
imgleft_array = new Array();
jQuery('.Image_left').each(function(){
imgleft_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgcenter_array = new Array();
jQuery('.Image_center').each(function(){
imgcenter_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgright_array = new Array();
jQuery('.Image_right').each(function(){
imgright_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
//... inside the eventhandler (entryindex = 'rel' of blogentry):
imgleft = imgleft_array[entryindex];
imgcenter = imgcenter_array[entryindex];
imgright = imgright_array[entryindex];
This works because it is not called inside the event handler and the sources are saved beforehand
BUT! I still cannot write the data, which is my aim:
jQuery('#bild_left').attr('src', imgleft);
jQuery('#bild_center').attr('src', imgcenter);
jQuery('#bild_right').attr('src', imgright);
UPDATE!!!
This is just crazy, I tried to write the data via usual javascript. This also works in FF, but no in IE8. Here really is some serious problem witt the attribute src:
document.getElementById('bild_left').src = imgleft;
document.getElementById('bild_center').src = imgcenter;
document.getElementById('bild_right').src = imgright;
alert(document.getElementById('bild_left').src);
This works in FF, but not in IE8, the attribute src remains undefined after writing! This seems to be not a jQuery problem at all!
children looks for immediate child elements only where as find looks for all the elements within it until its last child element down the dom tree. If you are saying find is working that means the element you are looking is not its immediate children.
Try to alert this jQuery(this).children('#Image_center').length see what you get.
FYI. Even when any element is not found jQuery will return an emtpy object it will never be null. So alert an emtpy object will always give you [object Object]. You should alwasy check for the length property of the jQuery object.
Try this
alert(jQuery(this).find('#Image_center').length);//To check whether element is found or not.
Bing Bang Boom,
imgright = jQuery(".Image_right",this).attr('src');
And why don't you easily use one working?
alert(jQuery(this).children('#Image_center').attr('src'));
change children to find
alert(jQuery(this).find('#Image_center').attr('src'));
It is probably the easiest solution, and when it work, why wouldn't you use it?
the problem is not in the attr('src') but in something else. The following snippet works in IE8:
<img id="xxx" src="yrdd">
<script type="text/javascript">
alert($('#xxx').attr('src'));
</script>
But if you for example change the the text/javascript to application/javascript - this code will work in FF but will not work in IE8
This has gotten so far,that I will sum up what we found out:
Inside the event handler the attribute src cannot be read in IE8 (FF works fine), neither with jQuery nor with usual javascript
The only way to get the data was to get it outside the handler, write it to an array and read it afterwards from the inside of the handler
But there was still no possibility to write to src (neither jQuery nor javascript worked - only for IE 8)
I've got it working by writing the img elemts themselves to the document, but the reason behind this problem is no solved
The new code
relcounter = 1;
imgleft_array = new Array();
jQuery('.Image_left').each(function(){
imgleft_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgcenter_array = new Array();
jQuery('.Image_center').each(function(){
imgcenter_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgright_array = new Array();
jQuery('.Image_right').each(function(){
imgright_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
//view entry
jQuery('.blogentry').live('click',function(){
// Get contents
entryindex = jQuery(this).attr('rel');
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
imgleft = imgleft_array[entryindex];
imgcenter = imgcenter_array[entryindex];
imgright = imgright_array[entryindex];
// Write contents
jQuery('#entryimages').html('');
jQuery('#entryimages').html('<img class="rotate" width="132" height="138" id="bild_left" src="'+imgleft+'" /><img class="rotateright" width="154" height="162" id="bild_center" src="'+imgcenter+'" /><img class="rotate" width="132" height="138" id="bild_right" src="'+imgright+'" />');
jQuery('.person').attr('src', profileimage);
jQuery('#g_fb_name').html(blogauthor);
jQuery('#g_titel').html(blogtitle);
jQuery('#g_text').html(blogtext);
});
So I am just not using .attr('src') in the event handler....
Try to make a delay:
jQuery(document).ready(function() {
setTimeout(function () {
jQuery('.blogentry').each(function(){
// your code...
});
}, 100); // if doesn't work, try to set a higher value
});
UPDATE
Hope, this code will work.
$('.blogentry img').each(function(){
alert( $(this).attr('src') );
});
UPDATE
I'm not sure, but maybe IE can't read classes with uppercase first letter...
Try to change ".Image_center" to ".image_center"
UPDATE
Check your code again. You definitely have some error. Try this jsfiddle in IE8, attr('src') is showed correctly. http://jsfiddle.net/qzFU8/
$(document).ready(function () {
$("#imgReload").click(function () {
$('#<%=imgCaptcha.ClientID %>').removeAttr("src");
$('#<%=imgCaptcha.ClientID %>').attr("src", "Captcha.ashx");
});
});
I´m developing a Javascript game and I have to place random coins in the HTML document. I have used this code so far:
createCoin() {
section=document.createElement("div");
section.innerHTML='<img src="./img/coin.png"/>';
document.body.appendChild(section);
}
This code simply places an image coin in the coordinates (0,0) of the document. What I want to do is access that recently created "div" and give it a random coordinate that I generate in another function so if I call several times the createCoin it creates several coins in the document. I can't use jQuery. Any ideas?
after create div element with id='coin' , to give the random position to div, use this:
<div id="coin" style="position:absolute">coin image</div>
<script language="javascript" type="text/javascript">
function newPos(){
var x=Math.random()*1000;
x=Math.round(x);
var y=Math.random()*500;
y=Math.round(y);
document.getElementById("coin").style.left=x+'px';
document.getElementById("coin").style.top=y+'px';
}
newPos();
</script>
we consider that createCoin() function execute once, on the onload() event. and then the newPos() function must be run.
Have createCoin return the div and then use it.
createCoin() {
section=document.createElement("div");
section.innerHTML='<img src="./img/coin.png"/>';
document.body.appendChild(section);
section.style.position = 'absolute';
section.style.left = '0px'; // units ('px') are unnecessary for 0 but added for clarification
section.style.top = '0px';
return section;
}
e.g.: var coin = createCoin(); coin.style.left = ???; coin.style.top = ???;
I'm having some trouble trying to get a fairly simple popupper to work. The idea is that the parent should open a popup window and then append a div in it.
The relevant parts of the code:
parent.html:
var childWindow;
function togglePref() {
childWindow = window.open("popup.html", "prefPopup", "width=200,height=320");
}
function loadPopupElements() {
var prefElements = document.getElementById("prefBrd").cloneNode(true);
var childDoc = childWindow.document;
var childLink = document.createElement("link");
childLink.setAttribute("href", "pop.css");
childLink.setAttribute("rel", "stylesheet");
childLink.setAttribute("type", "text/css");
childDoc.head.appendChild(childLink);
childDoc.body.appendChild(prefElements);
}
popup.html:
<head>
</head>
<body onload="opener.loadPopupElements();">
</body>
This works fine with Safari and Chrome, but for some reason IE refuses to append anything.
Ok, I managed to work around the problem with a uglyish solution using innerHTML. Apparently, as Hemlock mentioned, IE doesn't support appending children from a another document. Some suggested to take a look at the importNode() method but I seemed to have no luck with it either.
So, the workaround goes as follows:
parent.html:
var childWindow;
function togglePref() {
childWindow = window.open("popup.html", "prefPopup", "width=200,height=320");
}
function loadPopupElements() {
var prefElements = document.getElementById("prefBrd");
var childDoc = childWindow.document;
childDoc.body.innerHTML = prefElements.innerHTML;
}
popup.html:
<head>
<link href="pop.css" rel="stylesheet" type="text/css">
</head>
<body onload="loadElements();">
</body>
<script type="text/javascript">
function loadElements() {
opener.loadPopupElements();
}
</script>
This seems quite a nasty way to go because in my case the #prefBrd contains some input elements with dynamically set values, so in order for the popup.html to grab them, it has to do a bit of iteration at the end of the loadElements() function, which wouldn't have been necessary using appendChild.
I have a html page in which there is an image in anchor tag code is :
<img src="images/test.png" />
on body onload event i am calling a javascript function which dynamically changes the image . My code is:
<script type="text/javascript">
function changeImage()
{
document.getElementById('x').innerHTML= '<img src="images/test2.png" />';
}
</script>
This is working fine in firefox but not working in google chrome and ie. Please help..
try this:
<img id="y" src="images/test.png" />
in js
function changingImg(){
document.getElementById("y").src="./images/test2.png"
}
Tested in Chrome and IE.
Then try this: [hoping that id of <a> is available and have at least one img tag]
var x = document.getElementById("x");
var imgs = x.getElementsByTagName("img");
imgs[0].src="./images/img02.jpg";
try following instead of changing innerHTML.
function changeImage()
{
var parent = documeent.getElementById('x');
parent.getElementsByTagName("img")[0].src = "newUrl";
}
As others have indicated, there are many ways to do this. The A element isn't an anchor, it's a link. And no one really uses XHTML on the web so get rid of the XML-style syntax.
If you don't have an id for the image, then consider:
function changeImage(id, src) {
var image;
var el = document.getElementById(id);
if (el) {
image = el.getElementsByTagName('img')[0];
if (image) {
image.src = src;
}
}
}
Then you can use an onload listener:
<body onload="changeImage('x', 'images/test.png');" ...>
or add a script element after the link (say just before the closing body tag) or use some other strategy for running the function after the image is in the document.