Javascript: How to scroll through pictures with an incrementor? - javascript

I am extremely new to web programming, so please be patient as I am sure this is a basic question. I studied HTML and CSS, and began Javascript yesterday. I am unable to get this code to run correctly.
The way I was thinking to design it is to have a series of pictures 1.jpg, 2.jpg, 3.jpg etc and it would show one picture at a time. When you click a button it would go to the next picture using an incrementor.
I am looking first of all to make this work with as few changes as possible so I can see what I messed up on (learning and all that) and then I am sure there are shortcuts I could use which I'd love to learn. Please help if you can.
<html>
<head>
</head>
<body>
<script>
var picount=1;
document.write("<center>");
document.write("<img src=" + picount + ".jpg>");
document.write("</center>");
function upCount()
{
picount=picount+1;
}
</script>
<br><br><center>
<input type="button" onclick="upCount()" value="Next Picture" /></center>
</body>
</html>

You need to update the .src property on the image so it will load a new image. Here's one way to do that:
<script>
var picount=1;
document.write("<center>");
document.write("<img id='picture' src=" + picount + ".jpg>");
document.write("</center>");
function upCount() {
picount=picount+1;
document.getElementById('picture').src = picount + ".jpg";
}
</script>
<br><br><center>
<input type="button" onclick="upCount()" value="Next Picture" /></center>
And, in this code, there's really no reason to use document.write() to write out the initial HTML. It might as well be static HTML in the page like this:
<script>
var picount=1;
function upCount() {
++picount;
document.getElementById('picture').src = picount + ".jpg";
}
</script>
<center>
<img id="picture" src="1.jpg">
</center>
<br><br><center>
<input type="button" onclick="upCount()" value="Next Picture" /></center>

Related

how can i use input from a text box to change part of an iframe url?

<!DOCTYPE html>
<html>
<head>
<style>
body{
background-color:#ffffff
}
</style>
</head>
<body>
<!-- im attempting to make an iframe display a video the user types into
the prompt.-->
<input id="txtUrl" style="width:82%;" placeholder="youtube.com/watch?v=(finish the url)" name="url" type="text" />
<iframe src="www.youtube-nocookie.com/embed/(I WANT THE USERS INPUT
HERE)" allowfullscreen></iframe>
</body>
</html>
I got this far and my mind is going blank. every time i think of a possible solution, it just leaves my mind and i'm back to confusion. This is probably really easy to fix and i'm just stupid, but any help is appreciated.
You want to set src attribute of an iframe. Try doing that on keyup event. Then you can see the change immediately.
var textField = document.getElementById('txtUrl');
textField.addEventListener('keyup', function() {
document.querySelector('iframe').setAttribute('src', textField.value);
})
I haven't tested the code but you should get the basic idea on how to achieve what you want.
You just need to get input's value and then add this value to iframe's src attribute (add to existing value). Here is solution (if anything isn't clear - feel free to ask):
function changeSrc() {
const elem = document.getElementsByTagName("iframe")[0];
const inputVal = document.getElementById("txtUrl").value;
elem.src += inputVal
console.log(elem);
}
<input id="txtUrl" style="width:82%;" placeholder="youtube.com/watch?v=(finish the url)" name="url" type="text" />
<button onclick="changeSrc()">Change src</button>
<iframe src="www.youtube-nocookie.com/embed/" allowfullscreen></iframe>

Click on img link to change text inside a div

I have a page with 4 images and a div box containing some text. When I click on one of the images I want the text to change to something else.
My goal is to be able to click on each image and get information about them without making an entirely different HTML just for a slight change in one div.
<script type="text/javascript">
function changeText(){
document.getElementById('MyDiv').innerHTML = 'New Text';}
</script>
<img src="images/about.jpg" onClick="changeText()">
<div class ="text" id="MyDiv"><p>Welcome blabla</p></div>
This is the code I've been trying to make it work but it doesn't. I'd like to code it in Javascript as well.
Do you mean information about the image itself? If you want for example the value of src or perhaps title or some other attribute, you could do something like:
<script type="text/javascript">
function changeText(obj){
var div=document.getElementById('MyDiv');
div.innerHTML='';
var p=document.createElement('p');
p.appendChild(document.createTextNode(obj.title + ' '+ obj.src));
div.appendChild(p);
}
</script>
<img src="images/about.jpg" title="About Something" onclick="changeText(this)" style="cursor: pointer;" />
<div class="text" id="MyDiv">
<p>Welcome blabla</p>
</div>
The p tag will be overwritten to include the title and src of the image (in this example)
use Jquery html function
$('myImgClass').html('myText');

Sending variable to a function through javascript

i'm trying to send a variable through to a function when clicking an image, but can't get any of it to work. not sure where I am going wrong.?
jsfiddle http://jsfiddle.net/cibravo/rNGMR/
HTML
<input type="submit" value="send" onclick="alert('works')" />
<br/><br/>
<img onclick="alert('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
<br/><br/>
<!-- this doesn't work -->
<input type="button" value="send" onclick="myFunction()" />
<br/><br/>
<!-- this doesn't work -->
<img onclick="showhide('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
JS
function myFunction(){
alert("works");
}
function showhide(field){
alert(field);
}
Both of your examples that you say don't work will work provided the functions they call are globals, not contained within any scoping function.
The reason it's not working in your fiddle is that jsFiddle's (surprising) default is to wrap your JavaScript code in a window load event handler, like this:
window.onload = function() {
// your code here
};
...so your functions aren't globals. (I say it's surprising because waiting until the window load event runs, which is very late in the page load process, is not best practice.)
Here's an updated fiddle: http://jsfiddle.net/rNGMR/4/ As Juhana points out, you change tehs second drop-down box on the upper left to one of the "no wrap" options (I went with "no wrap - body").
For clarity, here's a complete all-in-one example: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Global Functions</title>
</head>
<body>
<input type="submit" value="send" onclick="alert('works')" />
<br/><br/>
<img onclick="alert('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
<br/><br/>
<!-- this doesn't work -->
<input type="button" value="send" onclick="myFunction()" />
<br/><br/>
<!-- this doesn't work -->
<img onclick="showhide('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
<script>
// Note that these are globals
function myFunction(){
alert("works");
}
function showhide(field){
alert(field);
}
</script>
</body>
</html>
More or less an alternity to your current approach
(which was solved while I wrote this.)
Please try avoid using the 'onclick' event when you work on bigger projects. It's usually better to keep HTML, CSS und JavaScript modularly separated.
When I encounter problems like this I usually use anonymous functions, who then call the
function with the right parameters.
This technique also solves the problem that everything needs to be global -- which is discouraged too.
It suited me well trough the last 3 years and around 15k lines of JavaScript code.
Here is an example:
http://jsfiddle.net/8jSaT/1/
<!-- HTML -->
<img id="btnSomething" src="http://firmakurser.studieskolen.dk/...">
// (plain) Javascript
var btn = document.getElementById('btnSomething');
// this is where the anonymous function comes in:
// Its only purpose is to redirect the onClick-Event
// and serve proper parameters
var btn.onclick = function() { showhide('works'); };
// Your code
////////////////
function myFunction(){
alert("works");
}
function showhide(field){
alert(field);
}

Javascript Persisting image visibility with a cookie/checkbox

this is my first question on Stack Overflow, I'm new to Javascript (have been teaching myself Python to get a feel for coding) and thought I'd try my hand at a simple web app to see how easy it is to translate my knowledge of Python into Javascript.
Basically the app will let you know when your favourite fruit etc is in season. So I have a list of checkboxes on one page 'fruitpicker.html' and corresponding images on another 'seasonalguide.html' (The images are just pictures of a calendar with the fruits season shaded etc).
I have a cookie that persists the checkbox state and a piece of external JS that toggles image visibility depending on the state of its corresponding checkbox.
Most of the cookie someone else was using on the web, so it works great, however the image vis JS is giving me trouble.
I've written what I think it should be but it didn't work and no matter how much I tinker around with it, nothing happens.
I'm sure it's something really dumb but anyway, here's the code...
The broken image vis JS:
function toggleVisibility(checkId, imageId) {
var imgEl = document.getElementById(imageId);
var checkEl = document.getElementById(checkId);
if (checkEl.checked) {
imgEl.style.visibility="hidden";
imgEl.style.display="none";
}
else {
imgEl.style.visibility="visible";
imgEl.style.display="inline-block";
}
}
By the way, if the line: var checkEl = document.getElementById(checkId);
is deleted the code works but image state doesn't persist. This is as far as I have gotten.
A few of the checkboxes in fruitpicker.html:
<html>
<head>
<title>Fruit Picker</title>
<script type="text/javascript" src="cookie.js"></script>
</head>
<body onload="restorePersistedCheckBoxes();">
<label for= "chklogo">Braeburn</label>
<input type= "checkbox"
id= "chkBraeburn"
onChange= "toggleVisibility('braeburnItem');
toggleVisibility('braeburnSeason');
persistCheckBox(this);" /><br>
<label for= "chklogo">Fuji</label>
<input type= "checkbox"
id= "chkFuji"
onChange= "toggleVisibility('fujiItem');
toggleVisibility('fujiSeason');
persistCheckBox(this);" /><br>
<label for= "chklogo">Golden Delicious</label>
<input type= "checkbox"
id= "chkgolldenDelicious"
onChange= "toggleVisibility('goldenDeliciousItem');
toggleVisibility('goldenDeliciousSeason');
persistCheckBox(this);" /><br>
<label for= "chklogo">Granny Smith</label>
<input type= "checkbox"
id= "chkGrannySmith"
onChange= "toggleVisibility('grannySmithItem');
toggleVisibility('grannySmithSeason');
persistCheckBox(this);"/><br/>
</body>
</html>
And here is the Seasonal Guide page:
<html>
<head>
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript" src="imageVisibility.js"></script>
</head>
<body>
<img id="imgGuide"
src="Images/Calendar/calendarHeader.png"
align="left"/>
<img id="braeburnItem"
src="Images/Produce/Fruit/BraeburnApple.png"
style="float:left; display:none;" />
<img id="braeburnSeason"
float="top"
src="Images/InSeason/InSeasonApr.png"
align="left"
style="display:none"/>
<img id="fujiItem"
src="Images/Produce/Fruit/FujiApple.png"
style="float:left; display:none;" />
<img id="fujiSeason"
float="top"
src="Images/InSeason/InSeasonMar.png"
align="left"
style="display:none;"/>
<img id="goldenDeliciousItem"
src="Images/Produce/Fruit/GoldenDeliciousApple.png"
style="float:left; display:none;"/>
<img id="goldenDeliciousSeason"
src="Images/InSeason/InSeasonFeb.png"
align="left"
style="display:none;"/>
<img id="grannySmithItem"
src="Images/Produce/Fruit/GrannySmithApple.png"
style="float:left; display:none;"/>
<img id="grannySmithSeason"
src="Images/InSeason/InSeasonApr.png"
align="left"
style="display:none;"/><br>
<table width="170px" height="70px">
<tr>
<td>
<a href="Main.html" id="back" title="about" class="button">
<img src="Images/Buttons/backButton.png" align="right">
</td>
</tr>
</table>
</body>
</html>
The question was getting long so I didn't include the cookie, but I can if it's useful.
Any help is appreciated, Thanks
I'm noticing two issues here.
First off, you're using two separate pages, but document.getElementById can only access the elements of the page you're on. So, your lines:
var imgEl = document.getElementById(imageId);
var checkEl = document.getElementById(checkId);
have to fail, because they are trying to access elements in the two pages. Whichever page you're running the script on, one of those lines will return null. Your question doesn't describe how the two separate HTML files relate to each other, so I can't help you fix this (Does the first load the second whenever a checkbox is clicked, or are the two pages loaded in frames or iframes of a parent page?).
The second issue is that your toggleVisibility function is defined with two parameters, but your code (for example):
onChange= "toggleVisibility('grannySmithItem');
toggleVisibility('grannySmithSeason');
calls the method (twice) with only one parameter. If we're talking about the same function (you might have a different function definition on each of the two pages), then the function can never identify the correct image, because the imageId is never supplied.

Simpler DIV/JavaScript update?

This is a newbie question: Can the following HTML/JavaScript code be further simplified by just keeping the DIV to be updated + the INPUT button?
<div id="main_section" name="main_section">
<div id="update_div">Old stuff</div>
<input type="button" value="Update" id="update_button"/>
</div>
<script type="text/javascript" src="/jquery.js"></script>
<script type='text/javascript'>
$("#update_button").click(function() {
$("#update_div").html("New stuff");
})
</script>
Thank you.
You can even inline JavaScript code in your HTML but that is a horrible practice unless you know exactly what you're doing. Reads as:
<div id="update_div">Old stuff</div>
<input type="button" value="Update" onclick="$('#update_div').html('...')" />
If you want to encode the knowledge of what gets updated with that on click, then you can encode that knowledge in the HTML elements itself.
<div id='target'>Old</div>
<input type='button' value='Update' data-target='#target' date-value='New' />
In jQuery's onload, define this for all such buttons:
Since the data seems to be static here, a better global approach might be to define the data on the elements itself, and setup all handlers in one global sweep of the DOM.
$(function() {
$(':button').click(function() {
var dest = $(this).attr('data-target');
var value = $(this).attr('data-value');
$(dest).html(value);
});
});
The above code still requires external JavaScript but only need it once for all such button and div elements on the page.

Categories