This is what I've tried, is there a better way of doing it? if so please LMK. Thanks :).
There's a div inside my HTML with an Id of 'content'. Each button have an eventListener and when clicked the eventListener checks the button's dataset and passes it through a dictionary and whatever value they get back will be the page the display inside 'content'.
HTML:
<body>
<div class="content"></div>
</body>
Javascript:
const content = document.querySelector(".content");
const pageOne = `This is page one of the three pages. <button id="next" onclick="showNextPage()" data-next="pageThree">Show Next Page</button> <button id="prev" data-prev="pageOne">Show Previous Page</button>`;
const pageTwo = `Behold the second page of the three pages. <button id="next" onclick="showNextPage()" data-next="pageThree"> Show Next Page</button><button id="prev" data-prev="pageOne">Show Previous Page</button>`;
const pageThree = `Finally the last page, page three of the three pages. <button id="next" onclick="showNextPage()" data-next="pageOne"> Show Next Page</button><button id="prev" data-prev="pageTwo">Show Previous Page</button>`;
content.innerHTML = pageOne;
const dict = {
"pageOne": pageOne,
"pageTwo": pageTwo,
"pageThree": pageThree,
}
function showNextPage() {
let button = document.getElementById("next");
content.innerHTML = dict[button.dataset.next];
}
function showPrevPage() {
let button = document.getElementById("prev");
content.innerHTML = dict[button.dataset.prev];
}
You can try solving the pagination with the counter variable,
and additional function for checking if the buttons should be disabled.
Also rewrite object to an array of objects, for easier accessing current page's content.
When it comes to templating as you wrote, consider using also maybe Handlebars or similar.
I played a bit to help you, if needed:
const content = document.querySelector(".content");
const next = document.querySelector("#next");
const prev = document.querySelector("#prev");
let counter = 0;
const dict = [{
contentText: "This is page one of the three pages."
},
{
contentText: "Behold the second page of the three pages"
},
{
contentText: "Finally the last page, page three of the three pages."
}
]
function showNextPage() {
counter += 1;
check()
}
function showPrevPage() {
counter -= 1;
check()
}
function check() {
// sets new html content
content.innerHTML = dict[counter].contentText
// disabling buttons
if (counter == 0) {
prev.disabled = true;
} else if (counter == 2) {
next.disabled = true;
} else {
next.disabled = false;
prev.disabled = false;
}
}
<body>
<div class="content">
This is page one of the three pages.
</div>
<button id="prev" disabled="true" onclick="showPrevPage()">Show Previous Page</button>
<button id="next" onclick="showNextPage()">Show Next Page</button>
</body>
Related
For my new project, I am trying to pass a link in a variable. I have buttons (multiple buttons let's say 50 buttons). So what it has to do is on button 1 click it should pass to var link = button1link.html and on button 2 click it should pass a variable to var link = button2link.html. making a specific function to each button is quite a long process so, In short, a specific button click should pass a specific link to var link . please help me out with it.
Thanks :D
<button id="button1" onclick= "seturl();">click here </button>
var link = "linkOfButton1.html"
You can put links into a data attribute of the button.
And add each click listeners by looping through the buttons.
let link
Array.from(document.querySelectorAll('button')).forEach(btn => {
btn.addEventListener('click', () => {
link = btn.dataset.link
console.log(link)
})
})
<button data-link="button1link.html">button1</button>
<button data-link="button2link.html">button2</button>
Pass the venet to your seturl() and then you can make the link.
function seturl(e) {
const id = e.target.getAttribute('id');
const name = id[0].toUpperCase() + id.slice(1);
let link = "linkOf" + name +".html";
alert(link);
}
<button id="button1" onclick= "seturl(event);">click here 1</button>
<button id="button2" onclick= "seturl(event);">click here 2</button>
Use a loop to set the links, location.href to forward the user to the specific page and also create the buttons (if they should be dynamic).
const links = ['https://example.com', 'https://google.com', 'https://stackoverflow.com'];
for (let link of links) {
const button = document.createElement('button');
button.innerText = 'Click here';
document.body.append(button);
button.addEventListener('click', () => {
window.location.href = link;
});
}
I have one image showing on my homepage and want the user to click next image button so the next image in the array displays. I have seen similar questions and have tried resolving the issue, but nothing seems to work. I think the code is correct I just can't seem to get the images to display when the user hits 'Next Image'. Any recommendations would be greatly appreciated.
JS:
var images = ["/aboutmepages/imagesAM/SSR.jpeg", "/aboutmepages/imagesAM/ATA.png",
"/aboutmepages/imagesAM/BC.jpg", "/aboutmepages/imagesAM/GCU.jpg"
];
var current = 0; //current image displayed
var change_img = document.getElementById("placeholder");
function next() {
if (current >= 0) {
current = images.length;
current++;
}
change_img.src = images[current].src;
}
HTML
<img src="/aboutmepages/imagesAM/SSR.jpeg" id="placeholder">
<div id="display">
<button class="button" onclick="next()">Next Image</button>
</div>
You have to add src as the image in the images array with using the current index
function next() {
if (current === images.length) current = 0;
change_img.src = images[current++];
}
NOTE: I've used lorem-picsum for demo purpose. You can add yours link
var images = [
"https://picsum.photos/200/300",
"https://picsum.photos/200",
"https://picsum.photos/200/300",
"https://picsum.photos/200",
"https://picsum.photos/200/300",
"https://picsum.photos/200"
];
var current = 0; //current image displayed
var change_img = document.getElementById("placeholder");
function next() {
if (current === images.length) current = 0;
change_img.src = images[current++];
}
const button = document.querySelector("button");
button.addEventListener("click", next);
<div id="display">
<button class="button">Next Image</button>
</div>
<img src="https://picsum.photos/200" id="placeholder" />
The key issue is this line:
change_img.src = images[current].src;
It should be
change_img.src = images[current];
as you don't have src properties on any of the elements in the array, just strings at array indexes.
Instead of checking that current >= 0 (we already know that it's going to be zero), check that current is less than the array length (because arrays use a zero-based index).
const images = [
'https://dummyimage.com/100x100/00ff00/000',
'https://dummyimage.com/100x100/0000ff/fff',
'https://dummyimage.com/100x100/000/fff',
'https://dummyimage.com/100x100/fff/000',
];
const placeholder = document.getElementById('placeholder');
const button = document.querySelector('button');
button.addEventListener('click', next, false);
let current = 0;
function next() {
if (current < images.length) {
placeholder.src = images[current];
++current;
}
}
next();
<button>Next</button>
<img id="placeholder" />
I'm working on a project where I generate a random var to create random scenes. One of them is location. I want it to be possible to generate a location with one button. Then press another button to generate a new location and when I press on the first button I want to get back the generated location I generated with that button
The function I generate the location with looks like this
function inhoudFunction()
{
var locs = ["movie", "park", "garden", "home"];
var loc = locs[Math.floor(Math.random()*locs.length)];
document.getElementById('inhoud').innerHTML="<h2>Locatie</h2>" + loc;
And these are the buttons I use to run the codes
<button type="button" onclick="introFunction()">intro</button>
<button type="button" onclick="midFunction()">mid</button>
To know if the button was pressed twice I used this code
function introFunction(){
if (introClicked == 1){
document.getElementById('introClicked').innerHTML="<div id=inhoud></div>";
}
else{
document.getElementById('introClicked').innerHTML="<div id=inhoud></div>";
inhoudFunction();
introClickedFunction();
}
And introClicked gets updated with this function
var introClicked = 0;
function introClickedFunction(){
introClicked = introClicked + 1;
}
But once I press the button twice I get nothing back
Save the generated value directly as a custom field of your <button> element.
In the example below, the element is passed to the click handler function as event.target. The function reads the gen_locations field. If it's not set, then it generates the random value and sets it.
window.addEventListener('DOMContentLoaded', _e => {
const locs = ["movie", "park", "garden", "home"];
document.getElementById('inhoud-button1').addEventListener('click', inhoudFunction);
document.getElementById('inhoud-button2').addEventListener('click', inhoudFunction);
function inhoudFunction(event) {
let genlocs = event.target.gen_locations;
if (!genlocs) {
genlocs = []
for (let i = 0; i < 2; i++) {
genlocs.push( locs[Math.floor(Math.random() * locs.length)] );
event.target.gen_locations = genlocs;
}
}
document.getElementById('inhoud').innerHTML = "<h2>Locatie</h2>" + JSON.stringify(genlocs);
}
});
<div id="inhoud"></div>
<button id="inhoud-button1">Inhound 1</button>
<button id="inhoud-button2">Inhound 2</button>
I've cleaned the code by avoiding inline javascript event handlers. Those are bad! :)
Edit: improved to show storing 2 generated randoms at once per button
I am trying to implement the following:
Change the image every time i click the button "next".
Right now the code gives me the very last image from the array book just after I click the button next once. Is there a way it can be done?
HTML code:
<body>
<div class="main_page">
<button type="button" id="start">Start</button>
<button type="button" id="next">Next</button>
</div>
</body>
JS code:
document.addEventListener('DOMContentLoaded', () => {
let book = [
{
name: 'page1',
img: 'img/page1.png'
},
{
name: 'page2',
img: 'img/page2.png'
},
{
name: 'page3',
img: 'img/page3.png'
}
]
const main_page = document.querySelector('.main_page');// with this variable I have conttrol of
// div with class .main_page
let mainImg = document.createElement('img') // similar to HTML tag <img>. this var-ble creates <img> tag in HTML Document
mainImg.setAttribute('src', book[0].img) // making attribute to <img> tag through JavaScript
main_page.appendChild(mainImg);// appending <img> tag to the div with class main_page
let next = document.getElementById('next');
const turnPage = (count) =>{
//if(mainImg.getAttribute("src") == 'img/page2.png') alert("hey")//mainImg.src = {firstpage}
next.addEventListener('click', () => {
if(mainImg.getAttribute("src") == book[count].img){
//alert("hey")
mainImg.src = book[count+1].img
}})
}
for(let i = 0; i< book.length; i++){
turnPage(i);
}
})
You have a few problems with your code, as others have pointed out. As Teemu said, you are adding 3 click listeners to the button. You also need to put the turn page function into your listener, instead of calling it outside. These are the main changes you need:
1: You need to declare a variable outside of the listeners and any loops to keep count of the pages
let count = 0;
2: Add a listener that will call your turnpage function on each click. In that listener, you need to check that the next page isn't greater than the total number of pages before calling turnPage- otherwise you will get an error when the code tries to access the image from a non-existent page.
(You could instead start again at page 1, but as you have a Start button I assumed that you will intend to use that instead of having a continuous loop).
next.addEventListener('click', () => {
if ((count+1) < book.length)
turnPage(count);
count++;
})
3: Finally, your turnPage function just needs to set up the next image
const turnPage = (count) => {
mainImg.src = book[count + 1].img
}
Here is the full working snippet:
document.addEventListener('DOMContentLoaded', () => {
let book = [{
name: 'page1',
img: 'https://lorempixel.com/output/animals-q-c-200-200-9.jpg'
},
{
name: 'page2',
img: 'https://lorempixel.com/output/animals-q-c-200-200-10.jpg'
},
{
name: 'page3',
img: 'https://lorempixel.com/output/animals-q-c-200-200-4.jpg'
}
]
const main_page = document.querySelector('.main_page'); // with this variable I have conttrol of
// div with class .main_page
let mainImg = document.createElement('img') // similar to HTML tag <img>. this var-ble creates <img> tag in HTML Document
mainImg.setAttribute('src', book[0].img) // making attribute to <img> tag through JavaScript
main_page.appendChild(mainImg); // appending <img> tag to the div with class main_page
let next = document.getElementById('next');
// set up your listener to turn the page on each click
next.addEventListener('click', () => {
let count = 0; // declare your variable for page count
// check if the next page is greater than the total number of pages
if ((count+1) < book.length)
turnPage(count);
count++;
})
// your turnPage function
const turnPage = (count) => {
if (mainImg.getAttribute("src") == book[count].img) {
mainImg.src = book[count + 1].img
}
}
})
<body>
<div class="main_page">
<button type="button" id="start">Start</button>
<button type="button" id="next">Next</button>
</div>
</body>
FYI I'm not sure what this line is for, but I've left it in, in case you need it for something you haven't included here:
if (mainImg.getAttribute("src") == book[count].img) {
Also, you could just use the count variable in your pageTurn without passing it in in the click listener. You could check if you are the the end in there - it all depends on how this fits in with the rest of what you need to do.
What Teemu said in the comments is right. I can't comment as my reputation is low. So providing the code here. Just remove turnPage function definition and for loop. And replace it with the code below.
let count = 0, len = book.length;
next.addEventListener('click', () => {
if(mainImg.getAttribute("src") == book[count].img){
count = (count + 1) % len;
mainImg.src = book[count].img
}
});
You can use array to store your image and then display it in your codes
But you also have to make sure you use <img src=""> tag
Example
<img src="" id="myImage">
<br />
<button type="button" id="next">Next</button>
//JavaScript Codes
//Get HTML Elements
let images = [];
let img = document.querySelector("#myImage");
let button = document.querySelector("#next");
let defaultIndex = 0;
//Make a function to be executed once you click the button
function makeIt() {
//Make sure defaultIndex won't be above your array
if (defaultIndex < images.length) {
//Then go to the next image using incrementation
defaultIndex += 1;
//Assign your new value to the img tag
img.src = images[defaultIndex];
}
You can even make previous feature by using decrement.
I hope this will help you. If you find any mistake, feel free to correct!
So I'm trying to make a slideshow where the user can click next to browse through pictures. I've created an array for the images:
var staff = new Array();
staff[0] = "/images/Isabelle.png";
staff[1] = "/images/Nook.png";
staff[2] = "/images/Timothy_Tommy.png";
staff[3] = "/images/Mabel.png";
staff[4] = "/images/Sable.png";
staff[5] = "/images/Labelle.png";
And a function for changing the images:
var i = 1;
function nextImage(){
document.getElementById("slide").src = staff[i];
if(i < staff.length)
i++;
else i = 0; //wraps around to first image
}
The addEventListener function call I added into a registerHandlers function that I initialize with onload:
document.getElementById("next").addEventListener("click",nextImage,false);
And the image and "next" button are placed in divs inside body:
<div class="container">
<img id ="slide" src="images/Isabelle.png" />
</div>
<div id="next">
<button type="button">Next</button>
</div>
I've tried looking up solutions and example code but I can't seem to make this work
Try adding the event handler as DHTML, so you don't have to wait for it to load the elements, just in case that's an issue:
<button type="button" onclick="nextImage();">Next</button>