Targeting HTML ID's and using jQuery to modify the content - javascript

I have this photo switcher below that I want to modify the HTML content using jQuery only. If you click on the "Show Next Photo" link jQuery will replace the "fruits.png" with another image example "airplane.png". (note: No changes to the HTML block is allowed).
I'm not sure how complicated it can be for jQuery. If I could avoid JavaScript, would be perfect.
<!--Do Not Change Inside this DIV-->
<div id="imageSwitcher">
<img src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png" id="fruits" />
<img src="https://homepages.cae.wisc.edu/~ece533/images/tulips.png" id="tulips" style="display:none;" />
<p>Show Next Photo</p>
</div>
Problem:
This is my script below and isn't working properly because when I refresh the page it just shows the airplane.png, and if I click on the link "Show Next Photo" it makes the airplane disapear.
Please give it a try at https://codepen.io/mrborges/pen/QQjJOq
<script>
//Go away fruits.png
document.getElementById('fruits').style.cssText = "display:none;";
$(document).ready(function () {
$('p').click(function () {
$('#imageSwitcher img').attr("src", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
//$('#fruits').toggle("hide");
$('#tulips').toggle("slow");
})
});
</script>

<script>
$(document).ready(function () {
let count = localStorage.getItem('count') || 0; // "0, 1, 2" or 0
count = parseInt(count, 10); //If we get it from storage then convert to number
const images = [
"https://homepages.cae.wisc.edu/~ece533/images/fruits.png",
"https://homepages.cae.wisc.edu/~ece533/images/tulips.png",
"https://homepages.cae.wisc.edu/~ece533/images/airplane.png"
];
$('#fruits').attr("src", images[count]);
$('p').click(function () {
count = (count + 1) % images.length;
$('#fruits').attr("src", images[count]);
localStorage.setItem('count', count);
});
});
</script>
The const images is a list (array) of links to the switch between. I added all the possible images and then i just change the src for each image. a pure jQuery solution would be very ugly, so you have to accept some vanilla JavaScript.
this line count = (count + 1) % images.length counts 1 up each time you click on the <p> if we reach the end of the images, then it just resets to 0. e.g. (2 + 1) % 3 = 0

Related

issue: image carousel skips 1st image

I have an automatic image carousel in javascript for my html website. The carousel has 5 images. The carousel works well on the first round, but on the second round of images, the 1st image doesn't appear. I'm not sure why? Please help if you can
<script>
(function(){
var imgLen = document.getElementById('gallery');
var images = imgLen.getElementsByTagName('img');
var counter = 1;
if(counter <= images.length){
setInterval(function(){
images[0].src = images[counter].src;
console.log(images[counter].src);
counter++;
if(counter === images.length){
counter = 1;
}
},5000);
}
})();
</script>
It works the first time because your first image, which I'm assuming is the displayed image, starts with the correct source.
It appears that you are overwriting the source of this image with the other sources. After the first round, the original source of the first image is lost.
At the moment, your image sources are probably something like:
1,2,3,4,5
2,2,3,4,5
3,2,3,4,5
4,2,3,4,5
5,2,3,4,5
for the first round, which is alright. Once the second round starts however, and for subsequent rounds, it would go something like this:
2,2,3,4,5
3,2,3,4,5
4,2,3,4,5
5,2,3,4,5
The simplest solution would be to store the first image as a 6th image, which would work with your existing code.
An alternative solution would be to store image sources in a JavaScript variable and use those as sources instead of referencing other elements.
It seems that your first image in the set images[0] has its src attribute overwritten every time the setInterval runs, so its source value has been lost. This means it won't be readable again. Rather than using the 0th item in the set to be the display target for your slideshow, try giving it a unique classname (<img class="slideshowTarget" src="...">) and selecting it individually like:
var slideshowTargetImage = document.querySelector('.slideshowTarget');
Rather than using imgLen.getElementsByTagName('img'), try adding a classname to the images you want to cycle in (<img class="slideshowImage" src="...">) and select them with something like:
var images = document.querySelectorAll('.slideshowImage');
Next, you'll want the image list to contain the original image again, or it won't be available in your image list. You should put that item at the end, so it'll be in the correct position when it's time for your slideshow to loop.
<div class="slideshow">
<img class="slideshowTarget" src="0.jpg" />
<div class="slideshowPreloadImages" style="display: none;">
<img class="slideshowImage" src="1.jpg" />
<img class="slideshowImage" src="2.jpg" />
<img class="slideshowImage" src="3.jpg" />
<img class="slideshowImage" src="0.jpg" />
</div>
</div>
Next, you can simplify your logic for the loop into one statement that you can run after you set the source on your image. The %, or "modulo" operator causes the counter to wrap back around to zero as soon as it grows past images.length - 1.
counter = (counter + 1) % images.length;
All together!
(function(){
var slideshowTargetImage = document.querySelector('.slideshowTarget');
var images = document.querySelectorAll('.slideshowImage');
var counter = 0;
var cycleSlideshow = function(){
var nextImageSource = images[counter].src;
slideshowTargetImage.src = nextImageSource;
console.log('nextImageSource', nextImageSource);
counter = (counter + 1) % images.length;
};
if (images.length) { // we can now test whether it's 0/falsy, becacuse the target is not part of the set!
setInterval(
cycleSlideshow,
1000
);
}
})();

Multiple countdowns jQuery and organize them depending the time left

I want to create a website with multiple countdowns activated by a click, some of them have different time, others the same. I need to organize them depending the time left. When one finish I need to return it to his original countdown value, so you can click again.
To understand better (I don't need the effects, I made them only for the example): http://i.imgur.com/lvcwbqm.gif
I have this: http://jsfiddle.net/m19aojmu/
Each countdown works independently of the others.
HTML
<div class="element" id="el1"><b>Elm 1</b> <span class="timeout">10</span> segundos</div>
<div class="element" id="el2"><b>Elm 2</b> <span class="timeout">100</span> segundos</div>
<div class="element" id="el3"><b>Elm 3</b> <span class="timeout">5</span> segundos</div>
Javascript
function timer(selector) {
var self = $(selector);
var sec = parseInt(self.find('span.timeout').text());
var interval = setInterval(function() {
sec--;
if (sec >= 0) {
self.find('span.timeout').text(sec);
} else {
clearInterval(interval);
}
}, 1000);
}
$("body").on('click', '.element', function() {
timer(this);
});
While each countdown have a different id (el1, el2, el3 ...) I don't know to detect which of them finished, therefore I don't know how to add a class when it start and end.
About the ubication, what should I do? Different classes for each location with position absolute?
I know it's a lot, but some help will be great.
Thank you very much.
Agusitn you code its like 95% correct, but you are setting the .text() into the sec variable wich is 0 or -1
Lets change the code a little bit
First lets take the actual value of the span DOM Element.
var actualTime = $('span.timeout').html();
console.log("the actual value when click is " + actualTime)
Later on the if statement we check when the actual span text its equal to 0
else if($(this).find('span').text() <= 0) {
console.log(sec)
var text = self.find('span.timeout').text(actualTime);
console.log(actualTime)
clearInterval(interval);
}
and when the .text() its === to 0, we set the actualTime variable to get back to the actual time.
here is the JsFiddle

Switching image with Next/Previous buttons

Is there any way to switch images using next/prev buttons with jQuery? Here's the code:
<div class="prevDiv">
<img src="images/prev.png" alt="previous" />
</div>
<div class="pic" id="picwebd">
<img src="images/portfolio/webdesign/webd1.jpg" class="portPic" />
</div>
<div class="nextDiv">
<img src="images/next.png" alt="previous" />
</div>
I tried modifying this code to my needs: http://jsfiddle.net/x5mCR/16/ but I haven't succeed. I think that incrementing and decrementing number in the image src would be enough, but I can't come up with decent code do this. Google doesn't help neither.
In case anyone reading this post want a different approach still using JQuery fadeIn, Im posting below the code for that.
Here you can find the fiddle for it.
Here's the Javascript Part
//At the start will show the first image
$('#fullimage img.fullimage:first-child').fadeIn();
//Keep track of the image currently being visualized
var curr = $('#fullimage img.fullimage:first-child');
$('#next').on('click', function() {
//Hide Current Image
curr.hide();
//Find Next Image
var next = curr.next();
//If theres no next image (is the last img), go back to first
if (next.length == 0) next = $('#fullimage img:first');
//Fade In
next.fadeIn();
//Save in curr the current Image
curr = next;
return false;
});
$('#prev').on('click', function() {
curr.hide();
var prev = curr.prev();
if (prev.length == 0) prev = $('#fullimage img:last');
prev.fadeIn();
curr = prev;
return false;
});
Here's the HTML part
<div id="fullimage">
<img class="fullimage" src="http://i.imgur.com/RHhXG.jpg" />
<img class="fullimage" src="http://i.imgur.com/p1L2e.jpg" />
<img class="fullimage" src="http://i.imgur.com/NsrI0.jpg" />
<img class="fullimage" src="http://i.imgur.com/Ww6EU.jpg" />
</div>
<label id="prev">previous</label>
<label id="next">next</label>
Here is dynamic and simple script reducing your html code
http://jsfiddle.net/x5mCR/32/
$("#thumbnail a").on('click', function (eve) {
eve.preventDefault();
var link = ($(this).attr("href"));
var content = '<img src="' + link + '"/>';
$("#fullimage").hide().html(content).fadeIn('slow');
});
Remove the anchors with class thumbnail and give the corresponding <img> tags the thumbnail class, then use jQuery click methods for the thumbnail class:
$(".thumbnail").click(function() {
$(".fullimage").src = $(this).attr("src");
});
Make sure you have a single .fullimage in the #fullimage div.
This isn't the same as a next / previous button - but it would fix the JSFiddle that you made.
http://jsfiddle.net/x5mCR/34/
var picNumber = 1;
$(".nextDiv").click(function() {
picNumber++;
if (picNumber > 3) picNumber = 1; // Change 3 to how many pictures there are.
$(".pic img").attr("src", "images/portfolio/webdesign/webd" + picNumber + ".jpg");
});
$(".prevDiv").click(function() {
picNumber--;
if (picNumber < 1) picNumber = 3; // Change 3 to how many pictures there are.
$(".pic img").attr("src", "images/portfolio/webdesign/webd" + picNumber + ".jpg");
});
If I understand correctly, you're trying to use the arrow keys to move back and forth between pictures...so if this is the case, I would recommend taking a look at this post: Binding arrow keys in JS/jQuery
Also, for your convenience, I just took the code from that post and combined it with the function in your fiddle to get this:
$(document).keydown(function (e) {
if (e.keyCode == 39) {
$(".fullimage").hide();
var next = $(this).next();
if (next.length > 0) {
next.fadeIn();
} else {
$('#fullimage img:first').fadeIn();
}
return false;
}
});
In testing it looks like it might need some modification, and also, you would obviously need to create a similar function for when the back button is pressed, but I think if I'm understanding your issue correctly this is a good starting place.

Cycle through a list of html files with button

I have a list of products say:
laptops/prod1.html
laptops/prod2.html
laptops/prod3.html
monitors/prod1.html
monitors/prod2.html
monitors/prod3.html
I would like a button on my page that 'cycles' through the available items.
No idea how to do this. Is this possible with javascript?
function nextProduct(incr) {
var href = window.location.href
, offset = (typeof(incr)==='undefined' ? 1 : incr);
window.location = href.replace(/(\d+)\.html/, function(m, g1) {
return (Number(g1) + offset) + '.html'
});
}
Then you can do something like:
var button;
button = document.getElementByID('next-button');
button.addEventListener('click', function() { nextProduct(1); });
button = document.getElementByID('prev-button');
button.addEventListener('click', function() { nextProduct(-1); });
Setup a main page, this should not be a static html page but in your server side language of choice.
Include jquery to a main page using a script tag (you can get jquery from http://jquery.com/).
Your html could look like this:
<div id='content'></div>
<div>
<a href='javascript:void(0)' id='prev' class='btn'>Previous</a>
<a href='javascript:void(0)' id='next' class='btn'>Next</a>
</div>
In your js file you would have something like this:
var currPage = 0;
var pageList = ["laptops/prod1.html","laptops/prod2.html", "laptops/prod3.html"];
var totalPages = pageList.length;
$(".btn").on("click",function(){
//if we are at the last page set currpage = 0 else increment currPage.
currPage = currPage < (totalPages - 1) ? ++currPage : 0;
var page = pageList[currPage];
$('#content').load(currPage);
});
Some points to consider:
You will want to decide if the first page gets loaded on the main page load or on click
You will need to set a js variable to keep track of the currently loaded page
You will need to add some method of storing all the possible pages (think an array). This can get printed out to a script tag on the page on page load.
You need to decide what happens when you hit the end of the line. You can either cycle around or grey out the appropriate link.
jquery on
jquery load

Javascript taking too long to load

The javascript of the div "intro" is loading at last. It's taking too long to load as the web page loads the bg image first and then loads the java script. Is there a way i can display "loading please wait" message in that "intro" div until it completely loads. I just want that the intro should load first.
Javascript code:
var tl = new Array(
"=======================",
" Welcome user, ",
" ###########################################"
);
var speed = 50;
var index = 0;
text_pos = 0;
var str_length = tl[0].length;
var contents, row;
function type_text() {
contents = '';
row = Math.max(0, index - 20);
while (row < index)
contents += tl[row++] + '\r\n';
document.forms[0].elements[0].value = contents + tl[index].substring(0, text_pos) + "_";
if (text_pos++ == str_length) {
text_pos = 0;
index++;
if (index != tl.length) {
str_length = tl[index].length;
setTimeout("type_text()", 500);
}
}
else setTimeout("type_text()", speed);
}
This is the script and its basically typing letter by letter in a text area in the div "intro". The problem is that it loads at last when the whole page has loaded. It starts printing the text after like 15 seconds or so.
There are "domready" events you can listen to on the document but seems that's not cross-browser.
Eg: Mozilla
document.addEventListener("DOMContentLoaded", methodName, false)
A better option is to use jQuery's .ready() event. They handle all cross-browser implementations.
Eg:
$(document).ready(function(){
//execute code here
});
//Shorthand
$(function(){
//...
});
See this related question for more on domready.
Load a page with the empty intro div, run the script with "loading please wait" then trigger an ajax request to load the rest of the page and update the page on onComplete event from the ajax request
Using jQuery
$(document).ready(function() {
// update div here
});
http://api.jquery.com/ready/
Or you could do that with
window.onload= (function() {
// update div here
};
You can use jquery for this by wrapping the content in a div tag and then another div that holds a loading image, something to this effect:
$(document).ready(function () {
$('#loading').show();
$('#divShowMeLater').load(function () {
$('#loading').hide();
$('#divShowMeLater').show();
});
})
Assume divShowMeLater is the div that contains all the content being loaded. The markup would look similiar to this:
<div id="divShowMeLater" style="margin-left:auto;margin-right:auto;text-align:center;" >
<div id="loading">Page loading...
<img src="images/ajax-loader.gif" alt="loading page..." />
</div>
</div>

Categories