I am trying to make an image change when I click on a piece of text on a website that I am building.
At this moment I have created a class called device with one of them being device active as shown below:
<div class="col-md-3">
<div class="device active">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
</div>
And then what i am currently trying to do is remove the class of active when I click on some text with the i.d of #search2. This is my whole jquery script so far:
$("#search2").click(function() {
var currentImage = $('.device.active');
var nextImage = currentImage.next();
currentImage.removeClass('active');
});
However this does not seem to remove the class of active and the image is still displayed? any ideas?
Your selection is done right and it is working for me (the active class is removed from that item). The problem must be somewhere else in your code.
Here is an alternative:
var activeDeviceIndex = 0;
$("#search2").click(function() {
var devicesContainer = $('.device');
$(devicesContainer[activeDeviceIndex]).removeClass('active');
activeDeviceIndex === devicesContainer.length - 1 ? activeDeviceIndex = 0 : activeDeviceIndex++;
$(devicesContainer[activeDeviceIndex]).addClass('active');
});
.device {
display: none;
}
.device.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="device active">
<p>Device 1</p>
</div>
<div class="device">
<p>Device 2</p>
</div>
<div class="device">
<p>Device 3</p>
</div>
</div>
<button id="search2">click</button>
Check on the following, the id on the button to click should be search2 and not #search2, may be just typo stuffs.
after that update your code as follows
/**
*#description - gets the next image to slide, if the last image is the current image, it will loop the sliding
*#param {Element} current - the currently active image
*#param {Boolean} islooped - boolean value indicating if a looping just started
*/
var nextImage = function(current, islooped) {
var next = islooped? current : current.nextSibling;
while(next && next.nodeName.toLowerCase() !== 'div') {
next = next.nextSibling;
}
next = next? next : nextImage(current.parentNode.firstChild, true);
return next;
};
$('#search2').bind('click', function(event) {
var current = $('.device.active').removeClass('active').get(0);
var next = nextImage(current, false);
$(next).addClass('active');
});
Related
I'm trying to update the HTML when a button is clicked.
I have tried to solve this issue for a few hours now and I don't know if I'm stupid, but the images are not changing.
const slider = document.querySelector(".slider")
const btn = document.querySelector(".next")
const btn2 = document.querySelector(".previous")
const images = ['car.jpg', `left.jpg`]
window.addEventListener("load", iniliatizeSlider())
function iniliatizeSlider(){
var x = 0
cars = ''
cars += `<div class="slide">
<img src="${images[x]}" alt"client">
<br><br>
</div>`
slider.innerHTML = cars;
}
btn.addEventListener("click", consoleMsg)
btn2.addEventListener("click", consoleMsg2)
function consoleMsg(){
x=1
}
function consoleMsg2(){
x=0
}
<section id="slider-section">
<div class="container">
<div class="subcontainer">
<div class="slider-wrapper">
<h2>client showcase</h2>
<br />
<div class="slider"></div>
<div id="controls">
<button class="previous">
<img src="left.jpg" alt="previous client" />
</button>
<button class="next">
<img src="right.jpg" alt="next client" />
</button>
</div>
</div>
</div>
</div>
</section>
I was expecting the image to change when the button was clicked, but the image stayed the same, but the value of x changed.
Your initialize function is running once, when the page loads and at that point you are setting the image source to 0 and you never change it after that. You need to adjust the image source within the functions that react to button clicks. Now you do update x in those functions but nothing is ever done with x after that point.
A couple of other things... With .addEventListener(), you pass a reference to the callback function, not invoke the function, so the line should be: window.addEventListener("load", iniliatizeSlider) <-- no () after the function name.
Also, you don't need to replace the HTML on the page to update the image, you only need to update the image's src property.
See comments below:
// Get a reference to an existing image element.
// No need to recreate the <img> element.
const img = document.querySelector(".slider img");
const next = document.querySelector(".next");
const prev = document.querySelector(".previous");
const images = ["https://cache.mrporter.com/content/images/cms/ycm/resource/blob/1252204/68e7f03297f41cb3ce41f15ec478f70f/image-data.jpg/w1500_q80.jpg", "https://play-lh.googleusercontent.com/VC7rta8PIK3MqmQG5c-F5CNJQ6cCv6Eb-kyBoUcQ2xj83dZVhn7YCj_GIWW8y7TnAMjU=w240-h480-rw"];
let currentIndex = 0; // Keeps track of which image is shown
next.addEventListener("click", function(){
// Check to see if we're at the end of the array
if(currentIndex === images.length-1){
currentIndex = 0; // Reset index
} else {
currentIndex++; // increase the index
}
img.src = images[currentIndex]; // Just update the existing image's source
});
prev.addEventListener("click", function(){
// Check to see if we're at the beginning of the array
if(currentIndex === 0){
currentIndex = images.length-1; // Reset index
} else {
currentIndex--; // decrease the index
}
img.src = images[currentIndex]; // Just update the existing image's source
});
img { width:50px; }
<section id="slider-section">
<div class="container">
<div class="subcontainer">
<div class="slider-wrapper">
<h2>client showcase</h2>
<br >
<div class="slider">
<!-- Here, we just put a static image element with the first image we want to see. -->
<img src="https://cache.mrporter.com/content/images/cms/ycm/resource/blob/1252204/68e7f03297f41cb3ce41f15ec478f70f/image-data.jpg/w1500_q80.jpg">
</div>
<div id="controls">
<button class="previous">
<img src="left.jpg" alt="previous client">
</button>
<button class="next">
<img src="right.jpg" alt="next client">
</button>
</div>
</div>
</div>
</div>
</section>
Call the function initializeSlider() on click of btn instead of consoleMsg().
I have 2 images displayed on a page. I want a message to appear when I click 1 image and it to disappear when I click the alternate one, then vice versa.
The jQuery code I created below seems to be working fine, but I am continuously getting an [object HTMLImageElement] message on the alternate image every time I click the one that is displaying the text.
$(document).ready(function(){
$("#gimp").click(function(){
var gimp = "Gimp message.";
var i = $("#qInkscape").text(inkscape);
if (i == true) {
$("#qInkscape").hide();
$("#qGimp").text(gimp);
} else {
$("#qGimp").text(gimp);
}
});
$("#inkscape").click(function(){
var inkscape = "Inkscape message";
var g = $("#qGimp").text(gimp);
if (g == true) {
$("#qGimp").hide();
$("#qInkscape").text(inkscape);
} else {
$("#qInkscape").text(inkscape);
}
});
});
And the html
<div class="mf-container">
<div class="mf-content">
<div class="row">
<div class="mf-third mf-center">
<img src="img/qualifications/gimp_g.png" class="mf-pic-unique mf-pic-
shadow mf-margin-top" id="gimp" alt="about gimp">
<p id="qGimp" class="mf-off-black-text"> </p>
</div>
<div class="mf-third mf-margin-top">
<p class="mf-center mf-off-black-text">Click on an image to learn more
about each technology</p>
</div>
<div class="mf-third mf-center">
<img src="img/qualifications/inkscape_G.png" class="mf-pic-unique mf-
pic-shadow mf-margin-top" id="inkscape" alt="about inkscape">
<p id="qInkscape" class="mf-off-black-text"> </p>
</div>
</div>
</div>
</div>
On the first slide of my slider I've got some text that changes within an interval.
This is the jQuery to do this:
<script>
var x = 0;
var text = ["STRATEGICALLY", "COST-EFFECTIVELY", "EFFICIENTLY", "EXCEPTIONALLY"];
var counter = 0;
var elem = document.getElementById("banner-change");
var intervalID = setInterval(change, 1500);
function change() {
jQuery(elem).fadeOut('slow', function() {
jQuery(elem).text(text[counter++]);
if (counter >= text.length) {
counter = 0;
}
jQuery(elem).fadeIn('fast');
if (++x === 5) {
window.clearInterval(intervalID);
}
});
}
</script>
The slider looks something like this (The shortened code):
<div id="myCarousel" class="hp-top carousel fade" data-ride="carousel" data-interval="6000">
<div class="carousel-inner">
<div class="item active"><img src="" alt="Chicago"/><div class="carousel-caption">
<div class="carousel-caption-inner">
<p class="slider-text small"><span class="slider-padding">What makes</span> us <span class="slider-green">specialists?</span></p>
<p class="slider-text">We just do ip</p>
<p class="slider-text"><span id="banner-change" class="slider-green">exceptionally</span></p>
</div>
</div>
</div>
So the words in <span id="banner-change" class="slider-green"> keep changing. This works fine. However, it only works for the first time the first banner is shown. Which makes sense as I'm clearing the interval as each word is only supposed to show once, but not sure how to do this so that every time the first banner shows it starts the interval again?
You can use the carousel evelts to trigger action.
e.relatedTarget will then refer to the slide, that is sliding into view.
So if you give it a unique id, you can identify it and run whatever action afterwards.
$('#myCarousel').on('slide.bs.carousel', function (e) {
if (e.relatedTarget.id === 'firstSlide') // do something
})
Online example of my goal:
I'm trying to display bike products on a category page. On each product there's a frame variant color, I'm displaying that using round divs.
When I click a color, the image should change as you can see on Specialized website: (underneath the product image) Specialized Example.
My own website
You can see my own example here: My own website example (scroll down till you see the product with multiple products).
My target functionality:
When I click the GREEN div I'd like to show picture 2 and when I click the RED div I'd like to see image 3, but as Default it will always be the firs
The first color = the first image
The second color = the second image
And so forth
My HTML:
<div class="frameColors">
<div class="frameColor" data-color="#95BD40" style="background-color:#95BD40"></div>
<div class="frameColor" data-color="#000000" style="background-color:#000000"></div>
<div class="frameColor" data-color="#C6352D" style="background-color:#C6352D"></div>
</div>
<a href="/produkter/cykler/mountain-bikes/specialized/epic-hardtails/epic-hardtail/">
<div class="categoryImage" data-frame-color="95BD40">
<img src="/media/1072/165519.jpg?anchor=center&mode=crop&width=500&height=350&rnd=131200748910000000" class="productImage">
</div>
<div class="categoryImage" data-frame-color="000000">
<img src="/media/1071/165518.jpg?anchor=center&mode=crop&width=500&height=350&rnd=131200746750000000" class="productImage">
</div>
<div class="categoryImage" data-frame-color="C6352D">
<img src="/media/1073/166762.jpg?anchor=center&mode=crop&width=500&height=350&rnd=131200749050000000" class="productImage">
</div>
</a>
My Foreach(s):
var imageIds = item.GetPropertyValue<string>("productImages").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var images = Umbraco.Media(imageIds);
<div class="frameColors">
#foreach (var bikeColor in images)
{
var color = bikeColor.GetPropertyValue("frameColor");
<div class="frameColor" data-color="##color" style="background-color:##color"></div>
}
</div>
<a href="#item.Url">
#foreach (var img in images)
{
<div class="categoryImage" data-frame-color="#img.GetPropertyValue("frameColor")">
<img src="#img.GetCropUrl("product image")" class="productImage" />
</div>
}
</a>
Based on Adeneo reply I managed to modify the code a little so it worked out as I wanted.
First, I added a css line: .categoryImage { display:none; } to hide ALL the product images.
I then added the script based on Adeneo's reply. I start off with targeting EACH of the .frameColor divs and inside that, I added this the following line to show the first image: categoryImage.first().show();
If the CSS line is not included, all of the product images will be displayed by default, so it was necessary to HIDE all the images and inside the script, show the first image.
$(function () {
$(".frameColor").each(function () {
var categoryImage = $(this).parent("div").next("a").find(".categoryImage");
categoryImage.first().show();
if ($(categoryImage).length > 1) {
$(this).on('click', function () {
var color = $(this).data('color').replace('#', '');
$(categoryImage).hide().filter(function () {
return $(this).data('frame-color') === color;
}).show();
});
}
else {
$(this).hide();
}
});
});
Credits goes to Adeneo for providing the original script.
I have a list of elements similar to simplified HTML below. When one of the images is clicked some JavaScript if fired, and the image that is clicked becomes this.theImage.
I now need to get the position of the image; for example if the first image was clicked, the position should be 1, if the second is clicked it should be 2, and so on.
I could use var elements = $('.image-preview', '#gallery');, to take a list of all elements with the image-preview class, and then loop through them and match the ID to the image, but that seems really inefficient.
Is there another way of achieving this task that is more efficient?
<div id="gallery">
<div class="image-preview">
<img id="image-1" src="http://www.mysite.com/image1.jpg" />
</div>
<div class="image-preview">
<img id="image-2" src="http://www.mysite.com/image2.jpg" />
</div>
<div class="image-preview">
<img id="image-3" src="http://www.mysite.com/image3.jpg" />
</div>
<div class="image-preview">
<img id="image-4" src="http://www.mysite.com/image4.jpg" />
</div>
</div>
Not sure I get it, you catch a click on the image like this
$('.image-preview img').on('click', function() {
});
and then to get the index you'd do
$('.image-preview img').on('click', function() {
var index = $('.image-preview img').index(this);
});
note that it's zero based
FIDDLE
You can make Array.prototype.indexOf do it for you:
var gallery = document.getElementById('gallery'),
els = [].slice.call(gallery.getElementsByTagName('img'));
gallery.onclick = function(e) {
if(e.target.tagName.toLowerCase() !== 'img') return;
var position = els.indexOf(e.target);
};
Demo