Javascript setTimeout is not working, what am i doing wrong? - javascript

<title></title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/javascript">
function showImage(image) {
document.getElementById("image").style.visibilty = "visible";
document.getElementById("image").src = images / GreenLight.jpg;
}
function startTimer() {
var con = confirm("Press a button");
if (con == true) {
x = setTimeout(function () { showImage('image') }, 1);
}
else {
x = "You pressed Cancel!";
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="header">
<h1> Page 1</h1>
</div>
<div id="menu">
<ul>
<li> Home </li>
<li class="here">Page 1</li>
<li>Page 2</li>
</ul>
</div>
<div id="content">
<form id="formpage1" method="post" action="default.htm"></form>
<button onclick="startTimer()">Click Here</button>
<div>
<img id="image" src=images/GreenLight.jpg style="visibility:hidden" />
</div>
</div>
<div id="footer">
</div>
</div>
</body>
</html>
I am trying to get an image to display 5 seconds after the "ok" button is clicked on the alert box. I am so confused as to what i am doing wrong.

You have to form a legal javascript string in this line to get the .src property assigned as you wanted. So change this:
document.getElementById("image").src = images / GreenLight.jpg;
to this:
document.getElementById("image").src = "images/GreenLight.jpg";
FYI, the error console would probably have been your friend here as this probably would have been a javascript error and would have given you the error and line number.
Your HTML should also use quotes:
<img id="image" src="images/GreenLight.jpg" style="visibility:hidden" />
And, if you want a 5 second delay, then you need to set the time to 5000 milliseconds:
setTimeout(function () { showImage('image') }, 5000);

Changed showImage functions as
function showImage(image) {
document.getElementById(image).style.visibilty = "visible";
document.getElementById(image).src = "images/GreenLight.jpg";
}
Your HTMLtag of img should be use quotes:
<img id="image" src="images/GreenLight.jpg" style="visibility:hidden" />

Related

HTML and Javascript picture change on button click

I am trying to get these pictures to swap when the button is pressed, the pictures are local to my computer and need to change in sequence. When I press the button, it just generates a new picture, I need them to interchange
<html>
<head>
<script>
var imgs=document.images;
function changeLight() {
var firstImage = imgs[0].src + "";
for(var i=0; i<imgs.length-1; i++){
imgs[i].src=imgs[i+1].src+"";
}
imgs[imgs.length-1].src=firstImage;
}
</script>
</head>
<body>
<div id="splash">
<img src="Traffic Light Red.gif" alt="" id="mainImg">
</div>
<body>
<div id="wrapper">
<div>
<img id="image" src="images/test" />
<br><br><br>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="Traffic Light Yellow.gif" hidden />
<img src="Traffic Light Green.gif" hidden />
<img src="Traffic Light Yellow2.gif" hidden />
</div>
</div>
</body>
Here is some code. It works by comparing the src attributes of the hidden images, not a very elegant technique, but it works. This method will also break if you add images before the last hidden image, so use with care.
Also remember to rename the files so that they have no spaces. On the web, spaces get turned into %20s when being requested, which tends to break things :)
Anyways, here’s the code.
<!doctype html>
<html>
<body>
<div id="splash">
<img src="TrafficLightRed.gif" alt="" id="mainImg">
</div>
<div id="wrapper">
<div>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="TrafficLightRed.gif" hidden>
<img src="TrafficLightYellow.gif" hidden>
<img src="TrafficLightGreen.gif" hidden>
</div>
</div>
<script>
function changeLight() {
var currentImg = document.getElementById("mainImg");
for(var i=1;i<3;i++) {
if(document.images[i].src == currentImg.src) {
currentImg.src = document.images[i + 1].src;
return;
}
}
currentImg.src = document.images[1].src;
}
</script>
</body>
</html>
A more robust technique would be to store an array of image links in your JavaScript, instead of the hacky hidden images. Brownie points for implementing that!
so you mean first come as third, second as first and third as second??
and again the same on next click??
check the fiddle http://jsfiddle.net/stdeepak22/hax3d8cv/
$(document).ready(
function(){
$('#nextImage').click(function(){
var firstImage = $('#AllImages img:first');
$(firstImage).remove();
$('#AllImages').append(firstImage);
});
});
UPDATE
pure JavaScript. for those who says "jQuery for just this? my my" ;)
http://jsfiddle.net/stdeepak22/0mcLcozk/
function f(){
var allImage = document.getElementById('AllImages');
var firstImage = allImage.getElementsByTagName('img')[0];
allImage.removeChild(firstImage);
allImage.appendChild(firstImage);
}
Refer the script :
<html>
<head>
<script>
var imgs=document.getElementsByTagName('img');
var init = 3;
console.log(imgs[2].src);
function changeLight(){
var target = document.getElementById('imaget');
var firstImage = imgs[0].src + "";
if(init < 5 ){
target.src = imgs[init].src;
init = init +1;
}
else{
init = 3;
target.src = imgs[init].src;
}
}
</script>
</head>
<div id="splash">
<img src="Traffic Light Red.gif" alt="" id="mainImg">
</div>
<body>
<div id="wrapper">
<div>
<img id="imaget" src="images/test" />
<br><br><br>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="Traffic Light Yellow.gif" hidden />
<img src="Traffic Light Green.gif" hidden />
<img src="Traffic Light Yellow2.gif" hidden />
</div>
</div>
</body>
This works for me. I would like to suggest you to use array values (image srcs) set in javascript instead of using hidden images.

how do you change img src with javascript depending on browser width?

I would like to change the source of the image element with the id of "front". I have a basic script at the top, but it doesn't work. I was just attempting to come up with something but I'm very bad at JavaScript.
<html>
<head>
<link rel="stylesheet" type="text/css" href="home.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="home.js"></script>
<script type="text/javascript">
var reswidth=screen.width;
if (reswidth<400){
var x = document.getElementsById("front");
x.src="../images/colbysmall.png"
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<div class="header">
<div class="navigation">
<ul>
<li><a id="home" href="">Home</a></li>
<li>Services</li>
<li>Portfolio</li>
<li>Contact</li>
<li></li>
</ul>
</div>
<div class="yellow"></div>
<div class="x"></div>
</div>
</head>
<body>
<div class="website">
<div class="logo"></div>
<img src="../images/ColbyFaceblack.jpg" id="front" width="100%" >
<div class="content">
<div class="menu"></div>
<div class="office"></div>
</div>
<div class="body2">
<img src="../images/simple_dashed_full.png" width="100%">
<div class="weboutline">
<img src="../images/web_outline.png" width="100%">
</div>
<div class="body2img2">
<img src="../images/portfolio.png" width="100%">
</div>
<div class="body2img3">
<img src="../images/blog.png" width="100%">
</div>
</div>
<div class="body3">
<img src="../images/body.png" width="100%">
<img class="touch" src="../images/get_in_touch_beige.png" width="50%">
</div>
<footer>
<img src="../images/footer.png" width="100%">
<div class="copyright"> copyright COLBY MOFFETT 2015 </div>
<div class="facebook"></div>
<div class="instagram"></div>
<div class="twitter"></div>
</footer>
</body>
</div>
</html>
This is right, but has to be executed on change of screen size:
$(function () {
$(window).resize(function () {
var reswidth=screen.width;
if (reswidth<400){
var x = document.getElementsById("front");
x.src="../images/colbysmall.png"
}
});
});
Also make sure you execute it inside the $(function () { }); to execute on the DOM loaded contents. So, to make sure it also executes when it gets loaded, you need to store it in a named function and execute it every time when the window is resized.
Your final code will be:
$(function () {
var reszWindow = function () {
var reswidth=screen.width;
if (reswidth<400){
var x = document.getElementsById("front");
x.src="../images/colbysmall.png"
}
};
reszWindow();
$(window).resize(reszWindow);
});
Since you are already using jQuery, the following could be one of the solutions:
$( window ).resize(function() {
if($( window ).width() < 400) {
$("img#front").attr("src","../images/colbysmall.png");
} else {
$("img#front").attr("src","../images/ColbyFaceblack.jpg");
}
});
(PS. Untested code) :)
changing image according to screen resolution:
$(window).resize(function() {
var scrWidth = $(window).width();
if(scrWidth < 500){
$('#myImage').attr('src', 'http://wallpaper-download.net/wallpapers/logo-wallpapers-google-chrome-background-wallpaper-33143.jpg');
}
if(scrWidth > 500){
$('#myImage').attr('src', 'http://www.bhmpics.com/download/google_colorful_background-1920x1080.jpg');
}
});
(random images from google)
Fiddle here: http://jsfiddle.net/59ehtLde/
Javascript aside, you can do this with just HTML5. Browser support isn't great, but isn't bad, either.
<picture>
<source media="(min-width: 400px)" srcset="../images/colbysmall.png">
<img src="../images/ColbyFaceblack.jpg">
</picture>
<p>With placeholders:</p>
<picture>
<source media="(min-width: 400px)" srcset="http://placehold.it/400?text=colbyfaceblack">
<img src="http://placehold.it/200?text=colbysmall">
</picture>

Why does my javascript-code to hide/show div-boxes not work?

I'm trying to hide/show the main-contentholders on my website based on what menu-option the reader clicks on. This seems like a simple thing to me, I've done it multiple times before but now it just won't work. My code looks like this:
<!DOCTYPE html>
<html>
<head>
<title id="titel">Mercedes F1</title>
<link rel="stylesheet" href="mercedes.css">
<meta name="viewport" content="width=device-width; initial-scale=1">
<script>
function sidbyte(p){
var p;
if(p == 1) {
document.getElementById("forare").style.display = "block";
document.getElementById("mercedes").style.display = "none";
document.getElementById("statistik").style.display = "none";
}
else if(p == 2) {
document.getElementById("forare").style.display = "none";
document.getElementById("mercedes").style.display = "block";
document.getElementById("statistik").style.display = "none";
}
else if(p == 3) {
document.getElementById("forare").style.display = "none";
document.getElementById("mercedes").style.display = "none";
document.getElementById("statistik").style.display = "block";
}
}
</script>
</head>
<body>
<div class="page">
<nav>
Förarbiografi
<img src="Media/Menu_icon.svg" class="menuicon" alt="MenuIcon">
Mercedes F1
<img src="Media/Menu_icon.svg" class="menuicon" alt="MenuIcon">
Statistik
</nav>
<div id="forare" class="main">
<h1 class="rubrik">Förare</h1>
<p>
</p>
</div>
<div id="mercedes" class="main">
<h1 class="rubrik">Mercedes F1 genom åren</h1>
<p>
</p>
</div>
<div id="statistik" class="main">
<h1 class="rubrik">Statistik</h1>
<p>
</p>
</div>
</div>
</body>
</html>
The main problem is that whenever you are clicking on the a tag the page reloads. So put # inside the href attributes of the a tags. Thats it.
Click Here
jsFiddle
Note : The local p declared inside the function is of no use as you are using the parameter. So better you remove that if you are only using the parameter, though it doesn't effect your code unless you refer to that with this keyword. Like,
this.p // refers to the local p you declared.
You're reloading the page each time the action is triggered, so the default state is returned, meaning that the transformation is no longer applied. By giving the <a> tag an href of # or javascript:void(0);, you can prevent the page refresh. Or even better, you can actually execute the JS from the href itself.
I actually recommend using javascript:void(0);, since it doesn't jump to the top of the page by default, while # does. However, that behavior can be prevented with a simple onclick="return false".
Codepen
Find the below code which i did using jQuery. It's very short and easy to understand.
HTML
<div class="page">
<nav>
<a class="one" href="#">Förarbiografi</a>
<img src="Media/Menu_icon.svg" class="menuicon" alt="MenuIcon">
<a class="two" href="#">Mercedes F1</a>
<img src="Media/Menu_icon.svg" class="menuicon" alt="MenuIcon">
<a class="three" href="#">Statistik</a>
</nav>
<div id="forare" class="main">
<h1 class="rubrik">Förare</h1>
<p>Content</p>
</div>
<div id="mercedes" class="main">
<h1 class="rubrik">Mercedes F1 genom åren</h1>
<p>Content</p>
</div>
<div id="statistik" class="main">
<h1 class="rubrik">Statistik</h1>
<p>Content</p>
</div>
</div>
JS
$('.one').click(function(){
$('.main').hide();
$('#forare').show();
});
$('.two').click(function(){
$('.main').hide();
$('#mercedes').show();
});
$('.three').click(function(){
$('.main').hide();
$('#statistik').show();
});
CSS
.main{
display:none;
}
JS FIDDLE DEMO

How to use onmousehover event on multiple elements?

<html>
<head>
<script>
function show_function() {
var example_image=document.getElementById("example_image");
example_image.src="example_one.png";
}
function hide_function() {
var example_image=document.getElementById("example_image");
example_image.src="example.png";
}
</script>
</head>
<body>
<div class="one" onmouseover="show_function()" onmouseout="hide_function()">
<img id="example_image" src="example.png">
</div>
<div class="two" onmouseover="show_function()" onmouseout="hide_function()">
<img id="example_image" src="example.png">
</div>
</body>
</html>
When I hover the mouse over first div,the image changes. But when I hover the mouse over second div then also the image from the first div changes.
Does anyone know how to do it only in javascript?
Like Danko said, ID must be unique. Next step will be to insert variables into your function:
<html>
<head>
<script>
function show_function(id, hide)
{
var example_image=document.getElementById(id);
if(hide){
example_image.src="example.png";
} else{
example_image.src="example_one.png";
}
}
</script>
</head>
<body>
<div class="one"
onmouseover="show_function('example_image1')"
onmouseout="show_function('example_image1', true)" />
<img id="example_image1" src="example.png">
</div>
<div class="one"
onmouseover="show_function('example_image2')"
onmouseout="show_function('example_image2', true)" />
<img id="example_image2" src="example.png">
</div>
</body>
</html>
Or you can go like this too:
<img src="example.png"
onmouseover="this.src='example_one.png';"
onmouseout="this.src='example.png';" />
Hope it helps!
You can do it like this:
show_function = function (container) {
container.childNodes[1].src = "example_one.png";
}
hide_function = function (container) {
container.childNodes[1].src = "example.png";
}
then in HTML, pass this to function:
<div class="one" onmouseover="show_function(this)" onmouseout="hide_function(this)">
<img id="example_image" src="example.png">
</div>
<div class="two" onmouseover="show_function(this)" onmouseout="hide_function(this)">
<img id="example_image" src="example.png">
</div>
I think you want the first child node [0] of the div. and pass the hovered object into the callback.
function show(e){
document.getElementById('label').innerHTML = e.children[0].id;
e.style.border = "solid 2px red";
}
function hide(e){
e.style.border = "0";
}
<div class="one" onmouseover="show(this)" onmouseout="hide(this)">
<img id="example_image" src="example.png" class="one" >
</div>
<div class="two" onmouseover="show(this)" onmouseout="hide(this)">
<img id="example_image" src="example.png" class="two">
</div>
<p id='label' ></p>

Can anyone figure out why my jquery function slide up and down is not working properly on my first li tag?

My javascript function doit() does not work properly. I dont know why? any suggestions?
I have java script code here but can update if the html needs to be looked at. Here is the code: This has been modified
<!DOCTYPE HTML>
<html>
<head>
<title>Something</title>
<link rel="stylesheet" type="text/css" href="default.css">
<script src="http://code.jquery.com/jquery-latest.js">
</script>
<script src="functions.js">
</script>
<script>
$(document.body).ready(function ()
{
$("#video").slideDown("slow");
$("#first").css("background-color","#CCC");
$("#second").click( function () {
$("#video").slideUp("slow",function() {
$("#first").css("background-color","#666");
});
$("#video2").slideDown("slow",function() {
$("#second").css("background-color","#CCC");
});
});
$("#first").click(doit("first"));
});
function doit(x)
{
if(x.equals("first"))
{
$("#video2").slideUp("slow",function() {
$("#second").css("background-color","#666");
});
$("#video").slideDown("slow",function() {
$("#first").css("background-color","#CCC");
});
}
else if(x == "second")
{
}
else if(x == "third")
{
}
}
</script>
</head>
<body>
<div id ="content">
<div id="header">
<h1>Picture</h1>
</div>
<span id="menu">
<ul>
<li id="first">Main Tab</li>
<li id="second"> Video Tab</li>
<li id="third">Third Tab</li>
<li id="fourth">Fourth Tab</li>
</ul>
</span>
<iframe id ="video" style="display:none" width="560" height="315" src="http://www.youtube.com/embed/Sv6dMFF_yts" frameborder="0" allowfullscreen></iframe>
<iframe id ="video2" style="display:none" width="560" height="315" src="http://www.youtube.com/embed/g16eL-_HlvI" frameborder="0" allowfullscreen></iframe>
<div class="square" style="position:absolute; left: 1000px; top:500px;"></div>
<div class="square" style="position:absolute; left: 1130px; top:500px;"></div>
<div class="square" style="position:absolute; left: 1160px; top:500px;"></div>
<div class="square" style="position:absolute; left: 1190px; top:500px;"></div>
<div class="footer">2012
</div>
</div>
</body>
</html>
When you do this:
$("#first").click(doit("first"));
The doit function will execute at once (i.e when that line is executed, not when #first is clicked), and its return value will get attached to the click handler. In this case nothing is returned, and consequently nothing happens when you click it.
What you want to do is this:
$("#first").click(function(){
doit("first");
});
Also, as others have mentioned, swap if (x.equals("first")) to if (x == "first")
You are doing if(x.equals("first"))
It should be if(x == "first")
Without any mention of an error or where you think the code is failing, I'd have to say that this line is probably not doing what you want:
if(x.equals("first"))
You'll probably want that to be this:
if(x == "first")
You want to check the equality of the value not the equality of the object reference.
As far as I know, the .equals() method doesn't exist. You need to do a comparison like so:
if(x === "first") {}
Here is a list of all methods available to String instances

Categories