change image SRC and Style - javascript

Hi I want to rewrite an image Src and Style element.
The image tag has an element called "data-orig-file" wich has the url that I want to write to the src element.
I came up with this but I'm not good at javascript:
function changeImageSrc(img) {
var newurl= document.getElementById("img").getAttribute('data-orig-file');
var oldurl= document.getElementById("img").src;
document.getElementById("img").src = img.src.replace(oldurl, newurl);
}
Now Secondly I want to grab the "Style" element with it's values from the grandparent div of the image and write that style to the image instead of the original style.
Finally I want to do these two things on all images inside a container div on a page when it is loaded (I suppose).
Any help is greatly apreciated!!
Thanks
update:
what I came up with so far is this:
function ChangeImageSrc() {
var image=document.getElementById("img");
var div=document.getElementById("LastPost");;
for each (image in div) {
var newurl= document.getElementById("img").getAttribute('data-orig-file');
var oldurl= document.getElementById("img").src;
document.getElementById("img").src = img.src.replace(oldurl, newurl);
}
}
window.onload = function()
{
ChangeImageSrc();
};
I also tried it with an "onload" event on the body element like this (instead of the wondow.onload part):
onload="javascript:ChangeImageSrc()
Both don't work this far :(
Ok AffluentOwl, here's the HTML:
<div class="gallery-group images-1" style="width: 677px; height: 507px;">
<div class="tiled-gallery-item tiled-gallery-item-large">
<a href="http://i0.wp.com/www.mydomain.com/wp-content/uploads/..../../image.jpg" class="zoom">
<img data-attachment-id="5786" data-orig-file="http://www.mydomain.com/wp-content/uploads/..../../image.jpg" data-orig-size="1333,1000" data-medium-file="http://www.mydomain.com/wp-content/uploads/..../../image-300x225.jpg" data-large-file="http://www.mydomain.com/wp-content/uploads/..../../image-1024x768.jpg" src="http://i0.wp.com/www.mydomain.com/wp-content/uploads/..../../image.jpg?resize=1191%2C893" align="left" title="shelter-childrens-farm" data-recalc-dims="1" style="width: 73px; height: 9px;">
</a>
</div>
</div>
As you can see there is a CDN prefix to the url that I'm trying to loose (for good reasons, it's opposed to me by wordpress and doesn't work for me).
The second thing is about the style of the image tag, that's somehow set to the wrong dimensions so I want to grab the right size from the first div (top of code).

Here's how you replace an images' src attribute with a url stored in an attribute on the image called data-orig-file when the page loads.
<html>
<script>
function ChangeImageSrc() {
var div = document.getElementsByClassName("gallery-group images-1")[0];
var images = div.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].setAttribute("src", images[i].getAttribute("data-orig-file"));
images[i].setAttribute("style", div.getAttribute("style"));
}
}
window.onload = ChangeImageSrc;
</script>
<div class="gallery-group images-1" style="width: 500px; height: 500px;">
<div class="tiled-gallery-item tiled-gallery-item-large">
<img src="a.jpg" data-orig-file="b.jpg" id="image_id" style="width: 100px; height: 100px">
<img src="c.png" data-orig-file="d.jpg" id="image_id" style="width: 100px; height: 100px">
<img src="e.png" data-orig-file="f.png" id="image_id" style="width: 100px; height: 100px">
</div>
</div>
</html>
It would probably be helpful for you to look into the element selection functions in Javascript.
getElementById
getElementsByClassName
getElementsByTagName
querySelector
You may even like to use jQuery which makes selecting elements much easier. In jQuery you could replace the <script> code with the following for the same result as above:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function() {
var div = $(".gallery-group.images-1");
var images = div.find("img");
images.each(function() {
$(this).attr("src", $(this).attr("data-orig-file"));
$(this).attr("style", div.attr("style"));
});
});
</script>

Related

append div to another div by uisng tag name?

I have a container called adcontainer, now I have another div which contains a video generated dynamically to the dom, this new div which are generated dynamically does not have id or class juts tag name,
Now I want to append this new divs to the adconatiner
Here is HTML
<div id="adcontainer"></div>
<div style="width: 100%; height: 100%">
<video src="videos/video.mp4" autoplay="true"></video>
</div>
Js
var adContainer = document.getElementById('#adcontainer')
var video = document.getElementsByTagName('video');
var parentEl = video.parentNode;
adContainer.appendChild(parentEl)
unfortunately, this is not working, what is wrong here?
getElementById() doesnt require #
getElementsByTagName() returns a HTMLCollection, so use [0]
var adContainer = document.getElementById('adcontainer')
var video = document.getElementsByTagName('video');
var parentEl = video[0].parentNode;
adContainer.appendChild(parentEl)
<div id="adcontainer"></div>
<div style="width: 100%; height: 100%">
<video src="videos/video.mp4" autoplay="true"></video>
</div>
You have to run javascript after page is loaded.
window.addEventListener('load', function() {
var adContainer = document.getElementById('adcontainer')
var video = document.getElementsByTagName('video');
var parentEl = video[0].parentNode;
adContainer.appendChild(parentEl)
});

I want to hide a parent element if the image contained is empty

I have a table with a cell that contains a div to hold an image.
What I want to do is if the image itself has an empty src value or if there is an error on loading the image, to then set the display of the parent cell to none.
The table will actually list a series of images in the page and not all will be mepty or show an error.
The code below shows the table cell... info within {} are in fact dynamic data values passed through as text literals. If the value for "img src" is in error or empty then I want to set the display for ID of the TD to "none.
<td style="text-align: center; vertical-align: top; width: 400px;" id="{tag_itemid}">
<div class="image_container">
<div class="border">
<div class="boxSep">
<div style="width: 250px; height: 250px; border-radius: 15px;" class="imgLiquidFill imgLiquid imgLiquid_bgSize imgLiquid_ready">
<a title="{tag_name_nolink}" target="_blank" href="{tag_itemurl_nolink}" style="display: block; width: 100%; height: 100%;">
<img src="{tag_image (small)_value}" />
</a>
</div>
</div>
</div>
</div>
Would also like to handle situation where I have just the single table on my page with 2 iamges in the table each in a div and I want to set display=none for each DIV subject to image src being invalid URL or if src="" - see example below
<table style="width: 100%;">
<tbody>
<tr>
<td>
<div class="image_container_no_rollover icg_4" id="hldr1">
<img src="http://lorempixel.com/400/200/" alt="">
</div>
<div id="hldr2" >
<img style="border: 0px none;" src="http://lorempixel.com/400/250/" alt="">
</div>
</td>
</tr>
</tbody>
Here's how to do it:
$(document).ready(function () {
$("td").each(function () {
var $img = $(this).find("img");
if ($img[0] === undefined) return;
var td = this;
$(this).find("img").on("error", function () {
$(td).css("display", "none");
});
});
});
Check it out: JSFiddle
There are several ways to achieve that. For instance:
$('td').each(function() {
if($(this).find('img').attr('src') == "your evaluator here"){
$(this).css('display', 'none');
}
});
Of course, make sure the whole DOM has been loaded before running that code.
I found someone who was able to provide me with the required solution for which you can see the working results below for both cases with much simpler examples.
In answering the first part... Hiding all table cells checking each image within each cell and hiding that cell if the image specified is invalid or if the src=""
$(document).ready(function() {
$("table").find("img").each(function(){
if(!$(this).attr("src")){
$(this).closest("td").hide();
}else{
var image = new Image();
image.src = $(this).attr("src");
if (image.width == 0) {
$(this).closest("td").hide();
}
}
});
});
Check it out: [JSFiddle] (http://jsfiddle.net/gregt57/wke7pbgm/11/)
In Answering the second part of my question... Hiding any element where its child contained an invalid image or where src=""
$(function() {
$("#tbl01").find("img").each(function(){
if(!$(this).attr("src")){
$(this).parent().hide();
}else{
$(this).load(function(){
// ... loaded
}).error(function(){
// ... not loaded
$(this).parent().hide();
});
}
});
});
Check it out at [JSFiddle]

loading a whole series of images using jquery

I am using this library and what I want to do is to dynamically load the entire series of images in to an element:
<div id="product" style="width: 640px; height: 300px; overflow: hidden;">
/* These images are loaded and appended to the div element dynamically
<img src="images/01.jpg" alt="" />
<img src="images/02.jpg" alt="" />
<img src="images/03.jpg" alt="" />
<img src="images/04.jpg" alt="" />
<img src="images/05.jpg" alt="" />
<img src="images/06.jpg" alt="" />
/*
</div>
and then call the j360 library to set it up:
jQuery(document).ready(function() {
jQuery('#product').j360();
});
after the images have been loaded.
I have only seen tutorials where one image is loaded like this....
Are there any techniques for loading and appending a bunch of images in order?
Thanks in advance
Not sure what you mean by "load", but you can simply append the img element to the parent div, and the browser will say, "Hey, there's an image with a src, let me go grab it."
Here a working example on JSFiddle
If I understand correctly, you want to label the div as loading until ALL of the images to be appended have been properly loaded. This is doable, but a little complicated.
I am assuming you are able to generate an ordered list of image URLs. If this is not the case, then you have some more grunt work to do.
Essentially what we want to do is have each image check off whether or not it has loaded. Once they have all loaded, we can called a done handler and you can replace the loading .gif with your product view. Let's do it.
HTML
<div id="product" style="width: 640px; height: 300px; overflow: hidden;"></div>
JavaScript
$(document).ready(function() {
var imageURLs = [ ... ]; // you need to generate this (not too hard)
var imagesLoaded = 0;
var images = [ ];
$.each(imageURLs, function(i, imageURL) {
var $img = $('<img/>').load(function() {
imagesLoaded++;
// See if this was the last image we need to load.
if (imagesLoaded == imageURLs.length) {
showProductView();
}
})
.attr('src', imageURL);
images.push($img);
});
});
var showProductView = function() {
var $product = $('#product');
$.each(images, function(i, $img) {
$product.append($img);
});
$product.removeClass('loading');
$product.j360();
}
Don't know if this is specifically what you're looking for in your question, but this plugin will notify you when a set of images are loaded, and allow to perform a callback function after each individual image loads, or the whole set:
http://www.farinspace.com/jquery-image-preload-plugin/
It works great.

Insert Iframe Into a Div Using Javascript - for Greasemonkey

I need to insert an iframe into a div using javascript. I need this written in javascript so I can use the code in a greasemonkey script (and greasemonkey only allows for javascript).
The greasemonkey script will be inserting AOL's search bar into various websites. I've included the working HTML code below so you can test it out to see what the end result is when this works.
Here is exactly what I need to do, written in HTML:
<div style="overflow: hidden; width: 564px; height: 43px; position: relative;">
<iframe src="http://aol.com" style="border: 0pt none ; left: -453px; top: -70px; position: absolute; width: 1440px; height: 775px;" scrolling="no"></iframe>
</div>
I need to make that HTML code work in greasemonkey, which requires it being written in javascript. Here is what I've got so far (with my final question beneath the "pseudo-code"):
var makeIframe = document.createElement("iframe");
makeIframe.setAttribute("src", "http://aol.com");
makeIframe.setAttribute("scrolling", "no");
makeIframe.setAttribute("border", "0pt");
makeIframe.setAttribute("border", "none");
makeIframe.setAttribute("left", "-453px");
makeIframe.setAttribute("top", "-70px");
makeIframe.setAttribute("position", "absolute");
makeIframe.setAttribute("width", "1440px");
makeIframe.setAttribute("height", "775px");
makeIframe.setAttribute("scrolling", "no");
var makediv = document.createElement("div");
makediv.setAttribute("height", "43px");
makediv.setAttribute("width", "564px");
makediv.setAttribute("position", "relative");
makediv.setAttribute("overflow", "hidden");
I already know how to either insert the iframe OR insert the div into the source code of the sites I need to insert it into, by doing this:
var getRef = document.getElementById("div-id-to-insert-element-before");
var parentDiv = getRef.parentNode;
parentDiv.insertBefore(iframe OR div, getRef);
What I CAN'T figure out how to do, is how to write the iframe INTO the div and then insert that div into the source code. That very last code snippet works for inserting either the div or the iframe into the source code, but I need the iframe inside the div, and then for that div to be inserted into the source code (using that last code snippet).
Any ideas?
1- you can use element.appendChild
makediv.appendChild(makeIframe);
2- Or append iframe as html into div like this,
makediv.innerHTML = '<iframe src="http://aol.com" style="border: 0pt none ;'+
'left: -453px; top: -70px; position: absolute;'+
'width: 1440px;'+
'height: 775px;" scrolling="no"></iframe>';
than insert makediv to where you want,
var getRef = document.getElementById("div-id-to-insert-element-before");
var parentDiv = getRef.parentNode;
parentDiv.insertBefore(makediv, getRef);
UPDATE:
You cannot set style with setAttribute function,
var makeIframe = document.createElement("iframe");
makeIframe.setAttribute("src", "http://aol.com");
makeIframe.setAttribute("scrolling", "no");
makeIframe.style.border = "none";
makeIframe.style.left = "-453px";
makeIframe.style.top = "-70px";
makeIframe.style.position = "absolute";
makeIframe.style.width = "1440px";
makeIframe.style.height = "775px";
var makediv = document.createElement("div");
makediv.style.height = "43px";
makediv.style.width = "564px";
makediv.style.position = "relative";
makediv.style.overflow = "hidden";
Using on page reload the page redirected to the src URL of the iframe.
To avoid this use sandbox iframe, like this:
<pre>
<code>
<iframe sandbox="allow-forms allow-same-origin allow-scripts" src="https://yoururl.com/"></iframe>
</code>
</pre>

javascript image rollover inside div

i have a single div 100px X 300px. What's the easiest way in JavaScript so when I hover over the div i show an image and then when i leave the div the image disappears.
for starters i thought the following would get me started but i can't seem to remove the image properly
<script type="text/javascript">
function MouseOver_Event(elementId) {
var imgToCreate = document.createElement('img');
imgToCreate.setAttribute('id', 'imgHandle');
imgToCreate.setAttribute('src', elementId + '.png');
imgToCreate.setAttribute('onmouseout', 'MouseOut_Event('+elementId+')');
var targetDiv = document.getElementById(elementId);
targetDiv.appendChild(imgToCreate);
targetDiv.removeAttribute('onmouseover', 'MouseOver_Event');
}
function MouseOut_Event(elementId) {
var imgToRemove = document.getElementById('imgHandle');
var targetDiv = imgToRemove.parentNode();
if (imgToRemove != null)
targetDiv.removeChild(imgToRemove);
targetDiv.setAttribute('onmouseover', 'MouseOut_Event(' + elementId + ')');
}
</script>
</head>
<body>
<div id="div1" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div2" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div3" onmouseover="MouseOver_Event(this.id)"><img src="Div3.png" alt="test" onmouseout="MouseOut_Event(parentNode's id or something)" /></div>
</body>
You're attaching your MouseOut_Event to onmouseover instead of onmouseout. But you probably don't need to be messing with dynamic event creation anyway; just add onmouseout="MouseOut_Event(this.id)" to the three divs and that should do it.
Why don't you use CSS instead ?
For example:
#div1{background:none;}
#div1:hover{background:url('src/div1.png') no-repeat;}

Categories

Resources