I'm trying to create a lightbox and I'm having trouble.
I think the problem is either because I have 2 window.onloads or because I'm trying to reference a newly created DOM element. I added some comments in the code below that explain what I'm trying to do.
//open lightbox
window.onload = showLargeImage;
function showLargeImage() {
var enlargeButton = document.getElementById("thumb1"); // thumb1 is a thumbnail you click to get the lightbox
enlargeButton.onclick = handleClick;
}
function handleClick() {
var lightboxContainerId = document.getElementById("lightboxContainer");
lightboxContainerId.innerHTML = '<div class="lightbox"><a class="reduceButton" href="#" ><img id="imageButton" class="largeImage" src="2012/images/web/web1.jpg" width="500" height="500" alt="Web Thumb 1"></a></div>';
} // the inner HTML creates the lightbox.
//close lightbox
window.onload = reduceImage; // i'm pretty sure that this windo.onload is the problem... or, that I'm referencing "imageButton" which is new to the DOM
function reduceImage() {
var reduceButton = document.getElementById("imageButton"); // you're supposed to click the big image in the lightbox to get close it.
reduceButton.onclick = handleReduceClick;
}
function handleReduceClick() {
var shadeId = document.getElementById("lightboxContainer");
shadeId.innerHTML = "say what"; // closing the lightbox simply strips everything out of the lightboxContainer
alert("oh yeah");
}
Here are a few reasons why your code is not working:
showLargeImage and reduceImage are missing invocation parentheses in the places where they are being assigned to window.onload. Without parentheses, window.onload is being assigned a function, but that function is not getting called. You should, for instance, have window.onload = showLargeImage();
As you suspected, the second window.onload is overwriting the first.
reduceButton is (as you also suspected) being assigned before it exists, causing an error.
Here is one solution that may work for you.
HTML:
<!DOCTYPE html>
<html><head><title></title>
</head><body>
View
<div id="lightboxcontainer"></div>
</body></html>
JavaScript:
window.onload = function() {
// click link to show
var enlargeButton = document.getElementById('thumb');
enlargeButton.onclick = function() {
var lightboxContainerId = document.getElementById('lightboxcontainer');
lightboxContainerId.innerHTML = '<img src="http://placehold.it/350x150"' +
'width="350" height="150 alt="Thumb 1">' +
'<p>Click image to hide.</p>';
};
// click image to hide
var reduceButton = document.getElementById('lightboxcontainer');
reduceButton.onclick = function() {
reduceButton.innerHTML = ''; // removes lightbox contents
};
};
Live demo: http://jsfiddle.net/ericmathison/BxwYY/7/
If the code is placed at the end of the <body> (or anywhere after your lightbox elements), just use this:
document.getElementById("thumb1").onclick = function () {
document.getElementById("lightboxContainer").innerHTML = '<div class="lightbox"><a class="reduceButton" href="#" ><img id="imageButton" class="largeImage" src="2012/images/web/web1.jpg" width="500" height="500" alt="Web Thumb 1"></a></div>';
document.getElementById("imageButton").onclick = function () {
document.getElementById("lightboxContainer").innerHTML = "say what";
alert("oh yeah");
};
}
This will do everything you want.
Related
So I'm fiddling with a fun idea for an offline website I'm currently trying to develop.
It'll be offline as it's meant to be practice for later study assignments and such.
My problem is the following: I have a javascript function that replaces a PNG with a GIF and after the animation it should redirect the person to another html I've made.
The source for the JS animation is mainly acquired from here already, but I cannot seem to make it work in the ways I originally intended.
The way it currently works is that I click the png and it'll turn into a gif (no problem there) but what I want is that it runs my js script and then redirect to another .html file (url).
The following is my HTML:
<object id="syringe">
<img src="img/syringe.png" height="750" alt="img/syringe.gif" class="center">
<h2>Click the syringe to inject yourself with a daily dose of puns and jokes</h2>
</object>
The following is the JS:
(function($) {
var getGif = function() {
var gif = [];
$('img').each(function() {
var data = $(this).data('alt');
gif.push(data);
});
return gif;
}
var gif = getGif();
var image = [];
$.each(gif, function(index) {
image[index] = new Image();
image[index].src = gif[index];
});
$('#syringe').on('click', function() {
var $this = $(this),
$index = $this.index(),
$img = $this.children('img'),
$imgSrc = $img.attr('src'),
$imgAlt = $img.attr('data-alt'),
$imgExt = $imgAlt.split('.');
if($imgExt[1] === 'gif') {
$img.attr('src', $img.data('alt')).attr('data-alt', $imgSrc);
} else {
$img.attr('src', $imgAlt).attr('data-alt', $img.data('alt'));
}
$this.toggleClass('play');
});
})(jQuery);
It is to my understanding that I can add a delay and then another function to something in the js - such as the following, which is what I intend to do, however cannot accomplish.
[FUNCTION HERE],1000,
function(){
window.location.href=myredirectionuri;
});
And that is my problem.
It looks like you want to have the gif display for a second or two and then redirect, right? If $this.toggleClass('play'); is the end, then just insert this right after it:
setTimeout(() => window.location.href = myredirectionuri, 1000);
That'll wait for 1000ms and then redirect to the new page.
In the animation script, after it changes to a gif, insert
setTimeout(function() {
/* redirect code */
}, /* length of gif in milliseconds */ )
I have a list of items (districts) on a page, and an iframe pulling in a map on the same page. When a user clicks on one of the districts, the JavaScript changes the source of the iframe to show a map of the district the user clicked.
My current code simply uses an "onclick" for each district, which then calls a function to change the source of the iframe.
I am wondering if I can simplify this code at all, possibly by using a loop? If I have 15 more districts to add to the page, will I have to add another "onclick" and another function for each one? Or is there an easier way that I am missing?
Simplified HTML:
<div id="districtlist">
Allen
Barren
Butler
<!--about 15 more links to follow-->
</div>
<iframe id="maparea" src="http://www.reddit.com"></iframe>
Javascript:
var a = document.getElementById("districtlist")
a.getElementsByTagName("a")[0].onclick = Allen;
a.getElementsByTagName("a")[1].onclick = Barren;
a.getElementsByTagName("a")[1].onclick = Butler;
//more lines...
function Allen() {
document.getElementById("maparea").src="http://www.youtube.com";
}
function Barren() {
document.getElementById("maparea").src="http://www.mentalfloss.com";
}
function Butler() {
document.getElementById("maparea").src="http://www.amazon.com";
}
//more functions...
I believe you could try this
var elems = document.getElementById("districtlist").querySelectorAll('a');
[].forEach.call(elems, function(elem) {
elem.onclick = function() {
var url = '';
switch(elem.innerText) {
case 'Allen':
url = "http://www.mentalfloss.com";
break;
case 'Barren':
url = "http://www.mentalfloss.com"
break;
case 'Butler':
url = "http://www.amazon.com";
break;
}
document.getElementById("maparea").src=url;
}
});
My teacher told me that I cannot put Onclick and OnMouseover etc in my html? I need to put it into my .JS fille? After some search on google everyone is doing the same thing like I'm? I can only use Javascript
Can anyone help me out?
<script type="text/javascript">
var pauseSlider=false;
var image = []
image[0]=new Image()
image[0].src = "./images/1.jpg"
image[1]=new Image()
image[1].src = "./images/2.jpg"
image[2]=new Image()
image[2].src = "./images/3.jpg"
image[3]=new Image()
image[3].src = "./images/4.jpg"
</script>
This is my preloading (html, can stay there)
<img src="./images/1.jpg" name="slide" onmouseover="pauseSlider=true" onmouseout="pauseSlider=false" onclick="slideNext()" width=960 height=500>
So this is my 'mistake' I have to put 'onclick' and onmouseover etc in my .JS fille, I don't know how and where!
var step = 1
document.getElementsByName'slide'
function slideit(){
if(!pauseSlider)
{
slideNext()
}
setTimeout("slideit()",2500)
}
function slideNext()
{
var slideimage = document.getElementsByName("slide")[0];
slideimage.src=image[step].src
if (step<image.length-1)
step++
else
step=0
}
This is my Javascript file (it's a imageslider)
I hope i've followed the rules, not sure about the 'code block'
I thank you!
Something like this:
var slideimage = document.getElementsByName("slide")[0];
slideimage.onclick = function() { ...... };
there many ways to bind events, described here
http://triaslama.wordpress.com/2008/07/22/four-ways-javascript-binding-event-listeners/
Add an id to your slide container...
<div id="slider">
<img src="./images/1.jpg" name="slide" onmouseover="pauseSlider=true" onmouseout="pauseSlider=false" onclick="slideNext()" width=960 height=500>
</div>
Then add your javascript like this...
window.onload = function(){
var slider = document.getElementById('slider');
slider.onclick = slidenext;
slider.onmouseover = function(){pauseslider = true;};
slider.onmouseout = function(){pauseslider = true;};
};
i suppose you might wanna try element.addEventListener(event, cbfunction, boolean);
https://developer.mozilla.org/it/docs/DOM/element.addEventListener
I'm trying to create a simple image swapper. So I have 20 images on the page, and 1 large one. I want the user to click one of the smaller images from the 20 and it be output into the place of the big image source.
I've only just started but even so my code doesn't seem to validate as the script fails before it even gets to the console.log. Also not sure if I'm using thisID correctly.
<img id='avatar-output' onclick='selectAvatar(thisID)' src='images/avatars/$number.png' />
<script>
function selectAvatar(thisID){
var imageSource = document.getElementById ("avatar-output").src;
console.log("Avatar source is " imageSource);
}
</script>
HTML:
<img id='avatar-output' src='images/avatars/$number.png' />
<img class='avatar-small' src='images/avatars/1.png' />
<img class='avatar-small' src='images/avatars/2.png' />
<img class='avatar-small' src='images/avatars/3.png' />
JS:
var els = document.getElementsByClassName('avatar-small'),
target = document.getElementById("avatar-output"),
handler = function() { target.src = this.src; };
for (var i=0; i<els.length; ++i) els[i].onclick = handler;
Demo
Or, if all small images are together, better use event delegation:
var target = document.getElementById("avatar-output");
document.getElementById("avatar-small-wrapper").onclick = function(e) {
if(e.target.tagName.toLowerCase() === 'img') target.src = e.target.src;
};
Demo
Notes
Better separation of content (html) and behavior (inline JS)
<script> element needs type="text/javascript" attribute
Avoid running JavaScript in global scope to avoid creating global variables, polluting window. Run in in a closure: (function(){ /* code here */ })()
You have a typo in it, change
var imageSource = document.getElementById ("avatar-output").src;
to
var imageSource = document.getElementById("avatar-output").src;
since there is a space where it shouldn't be.
Edit: oh and another one in the
console.log("Avatar source is " imageSource);
line. Add a + between your string and your variable like this:
console.log("Avatar source is " + imageSource);
Hey im having trouble with my javascript rollover. The image does not change. Ive had a look at some tutorials and i cant see where im going wrong.
Here is my code:
Home.xhtml
<img src="images/Weights.png" width="900" height="300" border="0" alt="Gym Equipment" name="gym"
onMouseOver="swapImage('gym','treadmill');" onmouseout="swapImage('gym','weights');"/>
newjs.js
// Pre load images for rollover
if (document.images)
{
treadmill = new Image
weights = new Image
treadmill.src = "images/Treadmill.png"
weights.src = "images/Weights.png"
}
function swapImage(thisImage,newImage)
{
if (document.images)
{
document[thisImage].src = eval(newImage + ".src")
}
}
How i tell the app where the js is:
document[thisImage].src = eval(newImage + ".src")
should be
document[thisImage].src = eval(newImage ).src
Please avoid using eval() as it is generally the slowest way to evaluate code and there are some circumstances where it introduces security risks depending upon where the data comes from that you're calling eval on.
You should be able to make this work:
HTML:
<img src="images/Weights.png" width="900" height="300" border="0" alt="Gym Equipment" name="gym"
onMouseOver="swapImage(this,'treadmill');" onmouseout="swapImage(this,'weights');"/>
Javascript:
// Pre load images for rollover
window.treadmill = new Image();
window.weights = new Image();
treadmill.src = "images/Treadmill.png"
weights.src = "images/Weights.png"
// this function must be defined globally
// (e.g. not defined inside any other function)
function swapImage(thisImage,newImageName) {
thisImage.src = window[newImageName].src;
}
Working demo here: http://jsfiddle.net/jfriend00/cv8tT/
Changes I made:
Removed the use of eval() and use window[name] to access global variables.
Changed the way swapImage() is called in the HTML to pass this so you can directly access the desired image.
Remove the if (document.images) checks since it is no longer used by the code.
FYI, all this could be done with CSS and background images with no javascript at all.
I would take a slightly different approach by taking the mouseover and mouseout attributes out of your image tag. This will help keep your code more maintainable.
I made a DEMO jsfiddle here
Note that I am using 3 images from Flickr, the default, one on mouseover, and one on mouseout. I hope this helps.
** Also note that the img tag now has an ID which is referenced in the bindings.
// Pre Load Images
var img1 = new Image();
var img2 = new Image();
img1.src = "http://farm4.staticflickr.com/3230/2953035318_b54956e7df_q.jpg";
img2.src = "http://farm4.staticflickr.com/3026/2992860864_aa9e8b0818_q.jpg";
// Event binding function
var bindEvent = function (el, eventName, eventHandler) {
if (el.addEventListener != null) {
return el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent != null) {
return el.attachEvent('on' + eventName, eventHandler);
}
}
// Mouseover binding
bindEvent(document.getElementById('surfer'), "mouseover", function (e) {
this.setAttribute("src", img1.src);
});
// Mouseout Binding
bindEvent(document.getElementById('surfer'), "mouseout", function (e) {
this.setAttribute("src", img2.src);
});