change image use javascript DOM - javascript

<html>
<head>
<script type="text/javascript">
var curimage = "cottage_small.jpg";
var curtext = "View large image";
function changeSrc() {
if (curtext == "View large image"||curimage == "cottage_small.jpg") {
document.getElementById("boldStuff").innerHTML = "View small image";
curtext="View small image";
document.getElementById("myImage")= "cottage_large.jpg";
curimage = "cottage_large.jpg";
} else {
document.getElementById("boldStuff").innerHTML = "View large image";
curtext = "View large image";
document.getElementById("myImage")= "cottage_small.jpg";
curimage = "cottage_small.jpg";
}
}
</script>
</head>
<body>
<!-- Your page here -->
<h1> Pink Knoll Properties</h1>
<h2> Single Family Homes</h2>
<p>
Cottage:<strong>$149,000</strong><br/>
2 bed, 1 bath, 1,189 square feet, 1.11 acres <br/><br/>
<b id="boldStuff" />View large image
</p>
<p><img id="myImage" src="cottage_small.jpg" alt="Photo of a cottage" /></p>
</body>
</html>
This is my coding I need to change the image and text the same time when I click it.
I use LTS, it shows the line document.getElementById("myImage")= "cottage_large.jpg";
is a wrong number of arquments or invalid property assigment.
Dose someone can help?
Bianca

You need to do the following steps
Change document.getElementById("myImage") to document.getElementById("myImage").src
Change <b id="boldStuff" />View large image to <b id="boldStuff">View large image</b>
This will solve the problem

You'll need to change the image source.
document.getElementById("myImage").src = "cottage_large.jpg";

You should change :-
<b id="boldStuff" />View large image
to following:-
<b id="boldStuff">View large image</b>
Looks like the getElementById does not work well for empty tags If you dont use ending tag.
Complete correct source:-
<html>
<head>
<script type="text/javascript">
var curimage = "cottage_small.jpg";
var curtext = "View large image";
function changeSrc() {
if (curtext == "View large image"||curimage == "cottage_small.jpg") {
document.getElementById("boldStuff").innerHTML = "View small image";
curtext="View small image";
document.getElementById("myImage").src= "cottage_large.jpg";
curimage = "cottage_large.jpg";
} else {
document.getElementById("boldStuff").innerHTML = "View large image";
curtext = "View large image";
document.getElementById("myImage").src= "cottage_small.jpg";
curimage = "cottage_small.jpg";
}
}
</script>
</head>
<body>
<!-- Your page here -->
<h1> Pink Knoll Properties</h1>
<h2> Single Family Homes</h2>
<p>
Cottage:<strong>$149,000</strong><br/>
2 bed, 1 bath, 1,189 square feet, 1.11 acres <br/><br/>
<b id="boldStuff">View large image</b>
</p>
<p><img id="myImage" src="cottage_small.jpg" alt="Photo of a cottage" /></p>
</body>
</html>

KooiInc is correct. but there is one problem with this statement.
IE6 will not honour document.getElementById("myImage").src.
so i suggest you use jquery instead like this.
$('#myImage').attr("src","the new source path");
Update:
#CMS: Please do check what i am tryin to say.
well i suppose there is a terrible misunderstanding here. for as far as i know IE6 never honours changing image source directly using ".src=" technique. I always used to use the following technique to achieve it if i can't use jquery.
document.getElementById('ImageId').style.cssText="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='newPath');";

Related

simple slide show in JS- buttons are not working properly

I want to create a basic page in html that displays a single image.
I also added two buttons Previous and Next. These buttons should allow the user to move forward or backward. Have 6 images in total. When the user reaches the end (or beginning when clicking on the back button) of the slide show, the slide show should not wrap around to the beginning (or end).
button onclick function for both the cases is not working. Its only getting displayed the first image as what mentioned in the img src attribute.
This is what I have done so far. I put all the images into an array and try to travel the array forward and backward side based on the button click.
<body>
<img src="img1.jpg" id="demo" style="width:400px;height:600px"/img>
<br/>
<input type="button" onclick="preImage()" value="Previous
">
<input type="button" onclick = "nextImage()" value="Next
">
<script>
var slider_content = document.getElementById("demo");
var image = ['img1','img2','img3','img4','img5','img6'];
var i = image.length;
function nextImage(){
if(i<image.length){
i=i+1;
}else{
i=1;
}
slider_content.innerHTML="<img src="+image[i-1]+".jpg>";
}
function preImage(){
if(i<image.length+1 && i>1){
i=i-1;
}else{
i=image.length;
}
slide_content.innerHTML = "<img src="+image[i-1]+".jpg">
}
</script>
</body>
Create a wrapper div to your image and change the innerHTML of the div.
<div id="demo" style="width:400px;height:600px">
<img src="img1.jpg">
</div>
An error needs to be corrected in the preImage function:
slide_content.innerHTML = "<img src="+image[i-1]+".jpg">
to
slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";
and also what Daniel said.

Update html image via javascript functions

I'm fairly new to javascript, and getting quite frustrated by the following code
<!DOCTYPE html>
<html>
<script>
var time = '0'
var area = 'neast'
function update_area(input) {
area = input;
load_updated_image(area,time);
};
function update_time(input) {
time = input;
load_updated_image(area,time);
};
function load_updated_image(area,time) {
var url = 'http://personal.psu.edu/kps5442/modelimages/hrrr_'+area+'_wetbulb'+time+'.png';
document.getElementById("theImage").src = url;
document.getElementById("url").innerHTML = url;
};
</script>
<body onload="load_updated_image(area,time)">
<p>URL Output:</p>
<p id="url"></p>
<font size = 4><b>Forecast Hour: </b>
<font size = 3>
<a href="#" onmouseover="update_time(0);" /> 00</a>
<a href="#" onmouseover="update_time(1);" /> 01</a>
<a href="#" onmouseover="update_time(2);" /> 02</a>
<img id="theImage" src=undefined width="850" height="600" />
<br> <font size = 4><b>Region Selection: </b>
<a href="#" onclick="update_area(neast);" /> Northeast</a>
<a href="#" onclick="update_area(seast);" /> Southeast</a>
</body>
</html>
I have 18 different "hours" of images for different regions across the US. The goal is to change the hour of the image when the hour links are moused over, and update the region when the region links are clicked.
The function update_time() works as expected, changing the image as I mouse over the links. However, the function update_area() fails with the following error:
"Uncaught ReferenceError: neast is not defined"
I'm not sure why this is happening, because the update_time and update_area functions are built in exactly the same way, and I globally defined the time and area variables at the start of the script.
Any help would be appreciated!
You have to put the arguments in quotes .
onclick="update_area('neast');"
onclick="update_area('seast');"
<!DOCTYPE html>
<html>
<script>
var time = '0'
var area = 'neast'
function update_area(input) {
area = input;
load_updated_image(area,time);
};
function update_time(input) {
time = input;
load_updated_image(area,time);
};
function load_updated_image(area,time) {
var url = 'http://personal.psu.edu/kps5442/modelimages/hrrr_'+area+'_wetbulb'+time+'.png';
document.getElementById("theImage").src = url;
document.getElementById("url").innerHTML = url;
};
</script>
<body onload="load_updated_image(area,time)">
<p>URL Output:</p>
<p id="url"></p>
<font size = 4><b>Forecast Hour: </b>
<font size = 3>
<a href="#" onmouseover="update_time(0);" /> 00</a>
<a href="#" onmouseover="update_time(1);" /> 01</a>
<a href="#" onmouseover="update_time(2);" /> 02</a>
<img id="theImage" src=undefined width="850" height="600" />
<br> <font size = 4><b>Region Selection: </b>
<a href="#" onclick="update_area('neast');" /> Northeast</a>
<a href="#" onclick="update_area('seast');" /> Southeast</a>
</body>
</html>
In JavaScript variables are not restricted to a single 'type', but a String will always be contained in quotes and a number will not. Also a variable cannot be, or start with, a number. This is why when you use a string as an argument it must be contained within quotes, otherwise it thinks you are sending a variable.
You're starting your document with <!doctype html> so you're saying you're writing HTML5, but there is a whole bunch of things that are incredibly wrong here due to use HTML3.2 and obsolete ways to invoke javascript.
Under modern HTML5 rules, there are no self-closing elements. It's not a hard error, but don't add that /> at the end of an <img.... Also <font> hasn't existed as element for 20 years now. It was removed in HTML4.1 in 1998. Then some semantics: if you need button functionality (i.e. clickable, but NOT navigating to some (part of a) page), use <button>. That's what it's for. Do not use <a>, and definitely not with href="#", because that's an active instruction for the browser to scroll to the top of the page. Finally, on...=... handlers are an ancient attribute that is unfortunately still supported, but you should never use. Use addEventListener in your Javascript, after you've declared all your HTML.
So let's just fix everything at the same time:
<!-- this line literally tells the browser "I am using HTML5" -->
<!DOCTYPE html>
<html>
<!-- always have a header section -->
<head>
<!-- no / at the end of meta elements -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Always just fill this in, it's good practice</title>
<style>
/* you want this in its own file, see the note at the end of this post */
h1 {
font-size: 100%;
font-weight: bold;
}
</style>
</head>
<body>
<!-- sectioning isn't mandatory, but extremely good practice -->
<section id="output">
<h1>URL Output:</h1>
<p>Forecast Hour:</p>
<div class="controls">
<!-- let's use data attributes, and be explicit about the values here -->
<button class="forecast update" data-value="0">0h</button>
<button class="forecast update" data-value="1">1h</button>
<button class="forecast update" data-value="2">2h</button>
</p>
<!-- if you've never see the figure/figcaption elements: they exist -->
<figure id="forecast-image">
<!-- no / at the end of this element -->
<img src="placeholder.jpg" width="850" height="600" alt="forecast map">
<figcaption></figcaption>
</figure>
</section>
<section>
<h1>Region Selection</h1>
<div class="controls">
<button class="area update" data-value="neast">Northeast</buton>
<button class="area update" data-value="seast">Southeast<button>
</div>
</section>
<!-- don't put your script in the page. put it in its own file -->
<script src="updates.js"></script>
</body>
</html>
And then we make a second file for the javascript called updates.js:
// this goes last, so that the DOM is done by the time you invoke your script.
var currentTime = 0;
var currentArea = `NorthEast`;
// this function doesn't need parameters: we already know what they are
function load_updated_image() {
var url = `http://personal.psu.edu/kps5442/modelimages/hrrr_${currentArea}_wetbulb${currentTime}.png`;
let figure = document.getElementById(`forecast-image`);
// update the image
let img = figure.querySelector(`img`);
img.src = url;
// update the image caption with a link
let caption = figure.querySelector(`figcaption`);
caption.innerHTML = ``;
let link = document.createElement(`a`);
link.href = url;
caption.appendChild(link);
}
// update the area, and called image update
function update_area(area) {
currentArea = area;
load_updated_image();
};
// update the time, and called image update
function update_time(time) {
currentTime = timel
load_updated_image();
};
// add the initial page load handling
document.addEventListener(`ready`, evt => load_updated_image());
// add the click handling for forecast time buttons
let forecastButtons = document.querySelectorAll(`button.forecastupdate`);
forecastButtons.forEach(button => {
// get the button's data-value
value = button.dataset.value;
// and then set up a click listener to update the forecast time
button.addEventListener(`click`, evt => update_time(value));
});
// add the click handling for forecast area buttons
let areaButtons = document.querySelectorAll(`button.area.update`);
forecastButtons.forEach(button => {
// get the button's data-value
value = button.dataset.value;
// and then set up a click listener to update the forecast area
button.addEventListener(`click`, evt => update_area(value));
});
And then to be even more proper, don't use <style>...</style> but make a new file called "forecast.css" and then link to that in your page using <link href="forecast.css" rel="stylresheet"> (note: this is still HTML5, you don't put /> at the end. Link elements simply don't have a closing tag)

Using counter/index to cycle through an array of images onclick

I am trying to create code that goes through a traffic light sequence when I click the button. I know there are a lot of people having the same problem however none of the solutions they got seem to work - I can only get the first asset (red traffic light) to display on the webpage and when I click the button nothing happens... Maybe I just need my code proof reading and there is something really obvious I've made a mistake on?
Here is my code:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Task 3</h1>
<img id="image" src="red.png" style="width:200px">
<input type="button" onclick="nextpic()" value="change image" >
<script>
var image = document.getElementById("image");
var counter = 0;
var trafficlights = [
"redamber.png",
"amber.png",
"green.png",
"red.png"
];
function nextpic(){
counter =counter+1;
if (counter == trafficlights.length){
counter = 0;
}
image.src = trafficlights[counter];
}
</script>
</body>
</html>

How do I add pictures to clickcounter text display? <image> <amount of clicks>

I've got a clickcounter onclick effect for my webpage, and when I click it, a text that says
You have clicked the button - ??? - times (??? would be the amount of clicks)
The onclick effect works great, but I was wondering if It's possible to change the display of the result. You see, I would like it to instead of having "You have clicked the button", have a miniature version of the picture, so it's like
miniature_image - ???
If that's at all understandable.
This is my current script for my button
Javascript
function clickCounter(){
var audio = document.getElementById("audio");
audio.play();
if(typeof(Storage)!=="undefined"){
if (localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else
{
localStorage.clickcount=1;
}
document.getElementById("result").innerHTML="<center><b>You have clicked the poop
</b>"+ localStorage.clickcount + "<b> times!</b></center>";
}
else{
document.getElementById("result").innerHTML="I'm sorry to inform you that your browser
does not support this web storage... I guess you could say that your browser is...
shit! awwww yeaahh!";
}
cursor: pointer;
}
HTML
<center>
<font face="chiller" color="#603913" "font size="300" <align="center"><b>Click the
poop!</b>
</center>
<center>
<p><picture onclick="clickCounter()"><picture
onmouseover="document.getElementById('touch').play()"><img src="poop.png"></button></p>
</center>
<audio id="audio" src="fart-01.wav"></audio>
<audio id="touch" src="sticky goo.wav"></audio>
<div id="result"></div>
I've already tried swapping out the "You have clicked the button" part with image source. like this
document.getElementById("result").innerHTML="<center><img src="poopamount">"+ localStorage.clickcount + "</center>";
but that just results in the button onclick effect disappearing. I've also tried using document.GetElementById("image"), but that didn't work either (not sure if i set it up correctly though)
How do I add a picture infront of the amount of clicks? I need it to be part of the result, because as you can see from my script, It's centered, and just positioning a picture wouldn't work because the amount of didgits change.
You can check out my webpage on the link on my stackoverflow profile if you think it would help.
Thanks to all in advance!
This might be an issue due to the time when the script is triggered.
Here is the fix and its working for me
<center>
<p>
<picture onclick="clickCounter()">
<picture onmouseover="document.getElementById('touch').play()">
<img src="http://inftek1.dyndns.org/daniel/Poop/poop.png">
</button>
</p>
</center>
<audio id="audio" src="http://inftek1.dyndns.org/daniel/Poop/fart-01.wav"></audio>
<div id="result"></div>
<audio id="touch" src="http://inftek1.dyndns.org/daniel/Poop/sticky goo.wav"></audio>
<div id="result"></div>
<script>
function clickCounter() {
var audio = document.getElementById("audio");
audio.play();
if (typeof (Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "<center>" + localStorage.clickcount + "</center>";
} else {
document.getElementById("result").innerHTML = "Your browser does not support the contents of this webpage";
}
//cursor: pointer;
}
</script>
Here is the fiddle
http://jsfiddle.net/b6ttzq7z/2/
Here's a link to a fiddle that i believe solves your problem: http://jsfiddle.net/62bwav2L/
In your code I see two divs with the same id, which is not allowed - ids must be unique
<div id="result"></div>
...
<div id="result"></div>
so - changed that:
<div id="resultPoopClick"></div>
...
<div id="result"></div>
and then you can go ahead and set your innerHTML with the img tag and all (not that that's a particularly elegant way to do this - but it will work)
document.getElementById("resultPoopClick").innerHTML = "<center>" + localStorage.clickcount + " <img src='http://inftek1.dyndns.org/daniel/Poop/poop.png' width='5%'/></center>";

do not allow to reload the page when popup is started with javascript

Hy,
i've got verry strange behavior (at least, i think it's strange...)
I've got a page where users can pick a color for background and a color for the text.
I've found a color picker on the internet, and that's working all just fine...
But every time i open the popup, the page reload. To test this i added a alert in script tags, and i got the alert when i acces the page and when i open the popup...
This is verry annoying, because the changes that users made will be lost ever time they open the popup...
Here is the button that fires the popup:
<button onclick="PopUp(\'background\')">gebruik de color picker</button>
note that this is part of a php string, so that's why the single quotes are escaped....
and this is the function PopUp:
function PopUp(keuze){
if(keuze == 'background'){
$('#clicked_one').val('background');
var de_waarde = $('#background_keuze').val();
$('#clicked_value').val(de_waarde);
}
else if(keuze == 'text'){
$('#clicked_one').val('text');
var de_waarde = $('#text_keuze').val();
$('#clicked_value').val(de_waarde);
}
window.open( './popup_color_picker.php', '_blank', 'width=500,height=500');
}
The popup page:
<?php
include '../config.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Color Picker</title>
<script src="<?php echo $root_off_page; ?>javascript/color_picker.js"></script>
</head>
<body>
<input type="text" class="color" id="color" value="">
<button onclick="klaar()">deze kleur wordt het</button>
</body>
</html>
<script>
var wat_is_geklikt = opener.document.getElementById('clicked_one').value;
var de_juiste_waarde = opener.document.getElementById('clicked_value').value;
function klaar(){
var de_gekozen_kleur = document.getElementById('color').value;
if(wat_is_geklikt == 'background'){
opener.document.getElementById('background_keuze').value = de_gekozen_kleur;
}
else if(wat_is_geklikt == 'text'){
opener.document.getElementById('text_keuze').value = de_gekozen_kleur;
}
self.close()
}
</script>
So does anybody see the problem why the main page (the opener) reloads???
Thanks
The default type of a button (if omitted) is submit which causes the reload of your page. Just change the type to button
<button type="button" onclick="PopUp(\'background\')">gebruik de color picker</button>
I was having the same issue with an < a > tag, I added type="button" to that and it fixed my issue, thanks for the help!

Categories

Resources