JSP code is written as below,
< img src='<%=imageURL%>' id='advt-image-top' border='0' alt=''" /><br/>
Where the value of imageURL is like,
http://1.2.3.4:5678/ads/avw.php?zoneid=1234567890&cb=INSERT_RANDOM_NUMBER_HERE
(Sample URL which fetches random advertisement image from Ad-Server)
Now, same JSP page contains javascript-code like below:
$(document).ready(function() {
var imgAd = new Image();
imgAd.src = '<%=imageURL%>';
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}
}
}
Above javascript code checks - if image returned from ad-server is of size 1x1, then it should be replaced with default-image.
Problem is, above entire code-snippet executes "imageURL" twice in order to fetch one image from ad-server : one to check whether image-returned-from-ad-server is of size 1x1 and other during tag execution.
How can I optimize above code so that "imageURL" is executed only once?
How can I assign Image() object of javascript (after 1x1 validation is passed) to JSP's 'advt-image-top' element?
Thanks in advance.
You just need a minor adjustment to your javascript code, there is no need to create an Image:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
}
However, the image might get loaded before the document ready fires and lose the onload event, so you might want to load the default url in your tag:
< img src='img/default_top.jpg' id='advt-image-top' border='0' alt=''" /><br/>
...and apply the remote url by code:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
}
EDIT: probably the best way is to remove the img tag altogether from the jsp and write everything with javascript. Supposing that the image is contained in an element with id "container":
$(document).ready(function() {
var imgAd = new Image();
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
imgAd.id='adv-image-top';
imgAd.border=0;
document.getElementById('container').appendChild(imgAd);
}
#dipanda, Thanks for your comments. Helped me solve my problem.
var $imgObj = $("<img/>",{src:"<%=imageURL%>"});
$imgObj.load(function(){
var imgJS = $imgObj[0];
if(imgJS.height == 1 && imgJS.width == 1){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}else{
if($("#advt-image-top")!=null && $("#advt-image-top")!=undefined){
$("container").append($imgObj);
}
}
};
Related
i have a simple function (up) here its an arrow and onclick is should check for image 1 in the div "gallerymain" and if its there it should show image 2. ELSE if image 3 is displayed and it suppose to show image 4 .
however for some unknown reason the == isn't working (i checked with alert ) , i also made sure that all is in the right case and path . the funny thing is that if i will use = instead of == it will work but it onclick it will show image 2 no matter what (even if image 3 is there ) i understand why (because i am assigning the path to the src . maybe somebody please take a fresh look on it and see what am i missing.
thank you!
function up () {
if
(document.getElementById("gallerymain").src ==
"../images/gallery/image1.jpg")
{
document.getElementById("gallerymain").src =
"../images/gallery/image2.jpg"
}
else if
(document.getElementById("gallerymain").src ==
"../images/gallery/image3.jpg")
{
document.getElementById("gallerymain").src =
"../images/gallery/image4.jpg"
}
}
img.src getter (as in img.src == '../img.jpg') returns absolute URL that is http://mysite.dev/img.jpg. img.src setter (as in img.src = '../img.jpg') amends relative URL to absolute.
getAttribute method returns exactly what was assigned. So try this.
if
(document.getElementById("gallerymain").getAttribute('src') ==
"../images/gallery/image1.jpg")
{
document.getElementById("gallerymain").src =
"../images/gallery/image2.jpg"
}
I am trying to make the elements clickable. However on clicking any of the <p> elements there is no alert box saying "hello". Please could you look at my code and possibly point me in the right direction?
function createLink(text, parentElement) {
var a = document.createElement('p');
var linkText = document.createTextNode(text);
a.appendChild(linkText);
a.onclick = function(e) {
e.preventDefault();
alert("hello");
};
parentElement.appendChild(a);
var br = document.createElement('br');
parentElement.appendChild(br);
}
var txtFile8 = new XMLHttpRequest();
txtFile8.open("GET", "http://www.drakedesign.co.uk/mdmarketing/uploads/date.txt", true);
txtFile8.onreadystatechange = function() {
if (txtFile8.readyState === 4) { // Makes sure the document is ready to parse.
if ((txtFile8.status == 200) || (txtFile8.status == 0)) { // Makes sure it's found the file.
allText8 = txtFile8.responseText;
arrayOfLines8 = allText8.match(/[^\r\n]+/g);
for (i = 0; i < arrayOfLines8.length - 1; i++) {
createLink(arrayOfLines8[i], document.getElementById("previousResultsList"));
}
}
}
};
txtFile8.send(null);
The script parses a text file online:
http://www.drakedesign.co.uk/mdmarketing/uploads/date.txt
Which is updated weekly and has dates written in it like so:
19/04/16
12/04/16
...
My script separates the text document into each line and stores it as an array. A for loop is then used to show the dates on the screen in a column which looks like so:
The problem is that on clicking each date an alert box is not shown saying "hello" and there seems to be no response at all.
All help is greatly appreciated.
I solved the issue!!
The problem was that I had divs with opacity 0 that were overlaying my parentElement! sorry stupid mistake!
This javascript code is supposed to switch when clicked an image to images from a folder within the html file folder.
After it gets to the last image, if you click again it resets to the first image.
Also there's a fade in and out effect on the appearing images.
It doesn't work and I suspect I wrote the path files to the images wrong somehow and the .attr doesn't change the src of the first image to the others.
Things to keep in mind = an extremely beginner programmer, just picked up html and css in about 2 days, I would appreciate any kind of help!
This is the code:
$(document).ready(function() {
var imageName = ["head.jpg", "head3.jpg", "head4.jpg"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$("#head1").attr("src", imageName[indexNum])";
//$(indexNum).css("height=600px,width=1000px")
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
$("#head1").fadeIn(500);
)};
)};
)};
You got a couple of errors in your code,
You swapped the closing ")" and "}" in the last two lines and you have a random " in the code.
Here's a working example:
$(document).ready(function() {
var imageName = ["http://placehold.it/200x200", "http://placehold.it/300x300", "http://placehold.it/400x400"];
var indexNum = 0;
$("#head1").click(function() {
indexNum = (indexNum + 1) % imageName.length; // this will count 0,1,2,0,1,2,0,1,2... always looping through your images
$(this).fadeOut(function() { //in this context, this refers to the #head, reading it from the DOM over and over again isn't efficient
$(this).attr("src", imageName[indexNum]);
}).fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="head1" src="http://placehold.it/200x200" alt="">
Just a small note: Your script (and mine) don't take into account loading times, this means that it will probably work fine on your computer, locally, but once you put it on a server, you will see the image fadeout, then fadein and still be the same image and then swap to the new image all of a sudden. This happens because it has some loading time. If you want to fix this you'll need some other events. Or you could load all images into the page and then just swap the one that is currently shown.
Even thought this has been answered, here is a fiddle with your original code corrected. http://jsfiddle.net/goqz3coj/
Its better to see how your code should work instead of been giving a different code
$(document).ready(function() {
var imageName = ["head.jpg", "head3.jpg", "head4.jpg"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$("#head1").attr("src", imageName[indexNum]);
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
$("#head1").fadeIn(500);
});
});
});
SECOND VERSION Waits for image load before showing again...
http://jsfiddle.net/goqz3coj/2/
By simply using .load you can wait for the image to load and then show.
$(document).ready(function() {
var imageName = ["http://placehold.it/200x200", "http://placehold.it/300x300", "http://placehold.it/400x400"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$( "#head1" ).load(function() {
$("#head1").fadeIn(500);
// Handler for .load() called.
});
$("#head1").attr("src", imageName[indexNum]);
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
});
});
});
Jonas Grumann took your image urls as easier to show with actual images.
So I am having issues with captioning my slide show using a javascript, can somebody let me know as to where I am going wrong. My code stands as this:
JavaScript Document
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
var img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
if( img.attr("src") == "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.attr("src") == "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.attr("src") == "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.attr("src") == "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.attr("src") == "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
HTML document
<div class="slides">
<img id="img1" src="">
</div>
<input type="image" src="images/Next.png" id="button" onClick="javascript:moveToNextSlide()" title="Next" >
<div id ="captionbar"></div>
Also to note, that I get this error within the "inspect element":
Uncaught TypeError: Cannot call method 'attr' of null
REVISED
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
window.onload = function(){
if( img.src === "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.src === "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.src === "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.src === "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.src === "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
}
The HTML Remains the same as before.
No error references however function does not write the text whatsoever.
Replace all img.attr('src') by img.src=="your image name".
For example:
img.src=="movieImages/img1.jpg"
As you are using pure JavaScript,you cannot use attr() which is method of JQuery.
attr() is a method brought by JQuery. If you are not using JQuery, you should keep using img.src. Another thing I noticed that might cause trouble : when you read .src from your image, you get the full path as a return (including your domain).
Your conditions would then become :
img.src === "http://yourdomain.com/movieImages/img1.jpg"
( And I just checked to be sure : http://www.w3schools.com/jsref/prop_img_src.asp mentions that the return value of img.src includes protocol and domain )
Also I think you should either define your function CaptionSlide inside moveToNextSlide so that it gains access to the updated img variable or not declare your img variable inside the moveToNextSlide function (so that the global variable gets updated instead)
Another point : you should make sure the DOM is loaded before querying elements from it (such as img) . To do so, wrap your code in a function, and assign it to the window.onload event :
window.onload = function() {
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
...
}
function CaptionSlide()
{
if( ... )
...
}
document.getElementById("button").addEventListener('click', moveToNextSlide);
}
and HTML for button :
<input type="image" src="images/Next.png" id="button" title="Next" />
I tested the following code in IE, Chrome, and Firefox and it does not work in any of them. I have read several questions about similar problems but they have not offered solutions that fix my example.
I am trying to create a pause/play button that interfaces with JWplayer (I also want it to interface with flowplayer, once I get the button working) and the image will change depending on which image is currently there. I also have a stop button that stops the player completely and changes the image of the pause/play button to pause.
Here is my current code:
<script type="text/javascript">
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML == imgtag2)
{obj.innerHTML = imgtag1;}
else
{obj.innerHTML = imgtag2;}
return;
}
function playimg()
{
document.getElementById('image1').innerHTML = '<img src=\'PLAY.png\'>';
return;
}
</script>
<div id="image1" href="#" onclick="changeimg(); jwplayer('mediaspace1').play(); jwplayer('mediaspace2').play(); jwplayer('mediaspace3').play(); jwplayer('mediaspace4').play();"><img src='PLAY.png'></div>
<div href="#" onclick="playimg(); jwplayer('mediaspace1').stop(); jwplayer('mediaspace2').stop(); jwplayer('mediaspace3').stop(); jwplayer('mediaspace4').stop();"><img src='STOP.png'></div>
The play/pause function works, and the first div WILL change into the pause img (so the javascript is going through) and it WILL change back into play if I click on the second div (stop function - triggers playimg() ) but it will not change back into the play image if I click on the pause button again.
For security reasons I can't link the website, but any help would be appreciated
It looks like all you really want to change is the SRC of the IMG tag, not necessarily the entire innerHTML. As machineghost mentions in his comment, there may be whitespace added or other changes to the full HTML that may make your comparison come out as false.
However, you could check if obj.src == "PLAY.png" and set the SRC attribute directly. Something like this:
function changeimg()
{
var obj = document.getElementById('image1');
var img1 = 'PLAY.png';
var img2 = 'PAUSE.png';
if(obj.src == img2)
{obj.src = img1;}
else
{obj.src = img2;}
return;
}
I think the innerhtml you are replacing in changeimg() is affecting the whole obj element, which is a div. So, if(obj.innerHTML == imgtag2) will return false since the div innerhtml is not imgtag2, but the next time you are going to call changeimg(), "obj" will be undefined because you replaced its innerhtml with an HTML code that doesn't have an id: {obj.innerHTML = imgtag2;}
Check the console to see if there's any javascript error, which it should, at if(obj.innerHTML == imgtag2)
rgds.
Just check whether PLAY is present or not and then change innerHTML according to it
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML.indexOf('PLAY') != -1)
{obj.innerHTML = imgtag2;}
else
{obj.innerHTML = imgtag1;}
return;
}