I have tried making a slideshow in js and its not working, all I get is the images displayed on the screen in order and the next and previous links just send me to the top of the page. I can't work out why, i know solutions that do work but I don't understand why this solution is not working. There are many solutions I have found online that are very similar to this one and they work, yet this one doesn't, I have only recently started js so I imagine its something silly I have missed. Here is the HTML: (edit: moved the to the bottom of the html body)
<html>
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="CSS/mainPageStyle.css">
</head>
<body style="background-color:white">
<div id="titleLogo"><h1>Custom Motorbikes</h1></div>
<nav>
<ul>
<li>Home</li>
<li>About Us</li>
<li>Full ride list</li>
<li>Custom ride</li>
<li>Contact Us</li>
<li>Login</li>
<li>Register</li>
</ul>
</nav>
<!-- front page slideshow: -->
<img src="images/bikePerson.jpg" class="slides" style="width:100%" />
<img src="images/bikePersonCountry.jpg" class="slides" style="width:100%" />
<img src="images/bikeRoad.jpg" class="slides" style="width:100%" />
Next Slide <br/>
Previous Slide
<!-- front page slideshow -->
<script type="text/javascript" src='JS/slideshow.js'></script>
</body>
</html>
here is the js:
var imgPos = 0;
var changeImage(0); //called so that images(except first one) are hidden intially
var imgs = document.getElementsByClassName("slides"); //creates an array, and fills it with all images with 'slides' class
var arrayLength = imgs.length;
function changeImage(x) {
var i = 0; //used for counting through 'for' loop
imgPos += x; //x will be either -1 or +1
if (imgPos > arrayLength){ //if user goes beyond last img
imgPos = 0; //go to first img
}
if (imgPos < 0){ //if user goes before first img
imgPos = arrayLength; //go to furthest img
}
for (i = 0; i < arrayLength; i++){
imgs[i].style.display = "none"; //this hides all the images
}
imgs[imgPos].style.display = "block"; //this then displays the image we want to see
return false;
}
Here are the errors:
Uncaught TypeError: Cannot read property '0' of undefined(…) slideshow.js:22
Uncaught TypeError: Cannot read property '1' of undefined(…)
Method 1 (Move the js to the bottom)
This will run after all of you dom has loaded.
<html>
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="CSS/mainPageStyle.css">
</head>
<body style="background-color:white">
<div id="titleLogo"><h1>Custom Motorbikes</h1></div>
<nav>
<ul>
<li>Home</li>
<li>About Us</li>
<li>Full ride list</li>
<li>Custom ride</li>
<li>Contact Us</li>
<li>Login</li>
<li>Register</li>
</ul>
</nav>
<!-- front page slideshow: -->
<img src="images/bikePerson.jpg" class="slides" style="width:100%" />
<img src="images/bikePersonCountry.jpg" class="slides" style="width:100%" />
<img src="images/bikeRoad.jpg" class="slides" style="width:100%" />
Next Slide <br/>
Previous Slide
<!-- front page slideshow -->
<script type="text/javascript" src='JS/slideshow.js'></script>
</body>
</html>
Method 2 (add document ready)
This will trigger the dom loaded event after your dom is loaded.
Note: You can not assign a function to a var var changeImage(0); You can assign the result of a function to a variable though: var myVar = changeImage(0);
var imgPos = 0;
var imgs = [];
function changeImage(x) {
var i = 0; //used for counting through 'for' loop
imgPos += x; //x will be either -1 or +1
imgPos = imgPos + 1 > imgs.length ? 0 : imgPos;
imgPos = imgPos < 0 ? imgs.length - 1 : imgPos;
for (let i = 0; i < imgs.length; i++) {
imgs[i].style.display = "none"; //this hides all the images
}
imgs[imgPos].style.display = "block"; //this then displays the image we want to see
console.log(imgs[imgPos])
return false;
}
document.addEventListener('DOMContentLoaded', event => {
imgs = document.querySelectorAll("img.slides"); //creates an array, and fills it with all images with 'slides' class
changeImage(0); //called so that images(except first one) are hidden intially
});
Related
I have created a side navigation bar and I am using it on two html pages using jquery. There is also an underline in the navigation bar which moves depending on the selected nav link. Below is the code for nav bar and html pages:
sidenav.html
<script type="text/javascript" src="script.js"></script>
<link href="design.css" rel="stylesheet" type="text/css" />
Page 1
Page 2
page1.html
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$("#nav-placeholder").load("sidenav.html");
});
</script>
<div id="nav-placeholder">
</div>
page1!
page2.html
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$("#nav-placeholder").load("sidenav.html");
});
</script>
<div id="nav-placeholder">
</div>
page2!
script.js: Script for movement of underline:
function ul(index) {
console.log('click!' + index)
var underlines = document.querySelectorAll(".underline");
for (var i = 0; i < underlines.length; i++) {
console.log(index*100)
underlines[i].style.transform = 'translate3d(0, ' + index * 70 + 'px, 0)';
}
}
Now what is happening is, underline was supposed to move down when switching to nav links using nav bar. But the issue is, as I go from page1.html to page2.html, screen refreshes and underline comes to its original position.
What my ask is, how to achieve this underline movement while switching between html pages.
I am not sure if my approach is right as I am new to UI. Please provide some references on how to switch between pages using nav bar and highlight selected nav.
Thank you.
You can change style on page load. You can get the page filename. I have assumed your sidebar.html content.
<div class="container">
<div id="nav-placeholder">
<nav>
<ul>
<li class="nav_link underline"><a href='page1.html'>Page 1</a></li>
<li class="nav_link underline"><a href='page2.html'>Page 2</a></li>
</ul>
</nav>
</div>
</div>
<script>
$(document).ready(function() {
// $("#nav-placeholder").load("sidenav.html");
var filename = location.pathname.substr(location.pathname.lastIndexOf("/")+1);
console.log(filename);
var underlines = document.querySelectorAll(".underline");
for (var i = 0; i < underlines.length; i++) {
console.log(underlines[i].querySelector('a').getAttribute('href'));
if(filename == underlines[i].querySelector('a').getAttribute('href') ) {
console.log('Yeah!!!');
underlines[i].style.transform = 'translate3d(0, ' + i * 70 + 'px, 0)';
}
}
});
</script>
I am new to javascript and I am trying to create a slideshow inside divs. However when I do it give me the error message
Uncaught TypeError: Cannot read property 'style' of undefined
at slideshow (script.js:14)
at script.js:1
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script type="text/javascript" src="script.js"></script>
<div id="wrapper">
<div id="content">
<div id="top">
<img class="slide" src="1.png" style="width:100%">
<img class="slide" src="2.png" style="width:100%">
</div>
<div id="left">
</div>
<div id="middle">
</div>
<div id="right">
</div>
</div>
</div>
</body>
</html>
This is my CSS code:
.slide {
display:none;
}
This is my Javascript code:
slideshow();
function slideshow() {
var index = 0;
var i;
var slides = document.getElementsByClassName("slide");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
index++;
if (index > slides.length) {
index = 1;
}
slides[index-1].style.display = "block";
setTimeout(slideshow, 2000);
}
I think the problem is that the javascript cannot access the images when they are in the div.
1. You are placing the <script> file before the slides. So when your script is executed the first time, the markup does not yet exist in DOM.
Because your slides do not exist, after the initial for (which does nothing), you get to this line
slides[index-1].style.display = "block";
But slides[0] does not exist, so it doesn't have a .style property.
2. You are reassigning the value of 0 to index each time you re-run the function, so it will always show the same slide: the first.
(3.) You chose display as the method to show/hide your slides, which is not animatable. Therefore, your slides will change abruptly, there's no possibility of transition.
(4.) In addition, just as a matter of personal choice, I prefer document.querySelectorAll('.slide') to document.getElementsByClassName("slide"). I don't know exactly why. Probably because it's shorter and maybe because it allows a more flexible selector syntax (classes, ids. attributes or any other valid css selector).
I need some with javascript code. I have a html code that read my list of image from in my image folder. I have to create a function button, so when I click on the next button, the next image will show. I have my code, but somehow it's not working. I have debug the code, there is no error, however the next image is not showing
Here is my code code:
var $ = function(id) {
return document.getElementById(id);
};
var listNode, captionNode, imageNode;
// Process image links
var i, linkNode, image;
var imageCache = [];
var imageCounter = 0;
var nexButton = function () {
listNode = $("image_list");
captionNode = $("caption");
imageNode = $("image");
var links = listNode.getElementsByTagName("a");
var imageCounter = 0;
for (i = 0; i < links.length; i++) {
linkNode = links[i];
// Preload image and copy title properties
image = new Image();
image.src = linkNode.getAttribute("href");
image.title = linkNode.getAttribute("title");
if (imageCounter < linkNode) {
imageCounter = imageCounter + 1;
image = imageCache[imageCounter];
imageNode.src = image.src;
captionNode.firstChild.nodeValue = image.title;
}
else {
alert("This is the last image");
}
}
};
window.onload = function() {
$("next").onclick = nexButton;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Slide Show</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="slide_show.js"></script>
</head>
<body>
<section>
<h1>Fishing Slide Show</h1>
<ul id="image_list">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<h2 id="caption">Casting on the Upper Kings</h2>
<p>
<img src="images/casting1.jpg" alt="" id="image">
</p>
<input type="button" value="Previous" name="previous" id="previous">
<input type="button" value="Next" name="next" id="next">
</section>
</body>
</html>
I'm trying to load a navigation bar from an external HTML file, and automatically set an anchor's tag class to "active" based on the current page.
Here's the code:
<html>
<head>
<title>Main</title>
<style>
.active {
background-color: green;
}
</style>
<script>
$(document).ready(loadAndSet());
function loadAndSet() {
loadBar();
setActive();
}
function loadBar() {
$('#bar').load('navigation.html');
}
function setActive() {
var aObjects = document.getElementById("bar").getElementsByTagName("a");
for (var i = 0; i < aObjects.length; i++) {
if (document.location.href.indexOf(aObjects[i].href) >= 0) {
aObjects[i].className = "active";
}
}
}
</script>
</head>
<body>
<div id="bar"></div>
<h1>Content Title</h1>
<p>Some content</p>
</body>
</html>
And here's navigation.html:
<ul>
<li>Home</li>
<li>Page 2</li>
</ul>
What am I doing wrong?
EDIT:
New code:
<html>
<head>
<title>Main</title>
<style>
.active {
background-color: green;
}
</style>
<script>
$(document).ready(loadBar());
function loadBar() {
$('#bar').load('navigation.html', setActive);
}
function setActive() {
$("#home").addClass("active");
}
</script>
</head>
<body>
<div id="bar"></div>
<h1>Content Title</h1>
<p>Some content</p>
</body>
</html>
And navigation.html:
<ul>
<li><a id="home" href="index.html">Home</a></li>
<li><a id="page2" href="page2.html">Page 2</a></li>
</ul>
The navigation bar doesn't even load...
Your navigation.html code is missing the closing ul-Tag: change the last <ul> to </ul>.
The second problem is a little bit more difficulty. The page index.html can have multiple different values in document.location.href!
It can be:
http://www.stackoverflow.com/index.html
or
http://www.stackoverflow.com/
or even
http://www.stackoverflow.com
Your code wouldn't work for the last two versions of the url.
The third problem is, that the load() function can take a few seconds, so that the code isn't loaded at the time your setActive() is executed. You have to wait until load is finished. You can achieve this by using a callback function:
$(document).ready(loadBar());
function loadBar() {
$('#bar').load('navigation.html', setActive);
}
function setActive() {
var aObjects = document.getElementById("bar").getElementsByTagName("a");
for (var i = 0; i < aObjects.length; i++) {
if (document.location.href.indexOf(aObjects[i].href) >= 0) {
aObjects[i].className = "active";
}
}
}
You can give every link an unique id and then use this little javascript at the end of every site.
<script type="text/javascript">
$(document).ready( function(){
$("#IFOFYOURLINK").addClass("active");
});
</script>
EDIT:
Try to use
function loadBar() {
$('#bar').load("navigation.html", setActive);
}
<html>
<head>
<meta charset = "utf-8/">
<title> My Student Life </title>
<link rel="stylesheet" href="Pan.css"/> <!--Links to the CSS -->
<script type = "text/javascript"> // JavaScript code
var slideimages = new Array() //SlideShow process begins
imgAlign = "center"
slideimages[0] = new Image() // create new instance of image object
slideimages[0].src = "Welcome.jpg" // set image src property to
slideimages[1] = new Image()
slideimages[1].src = "Code.jpg" //Image source
slideimages[2] = new Image()
slideimages[2].src = "books.jpg"
</script>
</head>
<body class ="Container" Background = "Background.jpg"> <!-- Background Images-->
<div class="headerMenu"> <!-- Div class for menus -->
<h1> My Student Life </h1>
<div id="menu"> <!-- created Menus-->
<ul>
<a href="WelcomePage.html"/> Welcome </a>
<a href=""/></a> <!--Menu links-->
<a href="Menu.html"/> Menu </a>
<a href=""/> </a>
</ul>
</div>
<header>
<h2 color = "white"> Welcome to my Student Life </h2>
</header>
<img src = "Welcome.jpg" width = "500" height ="300" id = "slide" > <!--Image -->
<script type="text/javascript">
var step=0 //starts
function slideit(){ //function called slideit
if (!document.images)
return
document.getElementById('slide').src = slideimages[step].src //Gets image by ID and follows the sliding process
if (step<2)
step++
else
step=0
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}
slideit() //Enable the function to perform
</script>
</body>
</html>
I am creating a project for one of my university course , I have created a slideshow using JS it works perfectly only problem is that the position of image is all the way to the left of screen . I tried padding-left in css but still didnt work I alsi created it in a div class and calld the class in CSS and a still no result. Sorry for my english.
Add following in your Pan.css :
.Container{
text-align: center;
}
For your question 2, just add margin-right to your image, the value is up to you:
img{
margin-right: 50px
}
Try adding the style below to your img tag:
<img src = "Welcome.jpg" width = "500" height ="300" id = "slide" style="margin: auto;" >