I'm trying to loop through images, and if the last image has a class of .active, I start again. However, it is not working at all:
http://jsfiddle.net/tmyie/VE75U/
img.click(function () {
$(this).removeClass('active').next('img').addClass('active');
if ($('.active').is(':last-child')) {
img.first().addClass('active');
}
});
To check if the last image has the class .active you have to almost reverse it and first get the last image and then check for the class, and since the last-child isn't an image, that wont work
if ( $('.module.m-slide img:last').hasClass('.active') ) { ...
You have 2 issues in your code:
When you click on last image this code:
$(this).removeClass('active').next('img').addClass('active');
Will not add active class to anything, because .next('img') will return an empty array. So next line will not work too:
if ($('.active').is(':last-child'))
Because there is no active elements.
I believe you need to fix it in the following way:
if ($(this).is(':last-child'))
Next thing: none of your images can be a :last-child, because even your last image is not a last child! Look carefully at your html code:
<div class="module m-slide">
<img src="http://placehold.it/1200x800&text=1" alt="" />
<img src="http://placehold.it/1200x800&text=2" alt="" />
<img src="http://placehold.it/1200x800&text=3" alt="" />
<div class="m-slide-ctrl"></div>
</div>
Your last child is <div class="m-slide-ctrl"></div>
I suggest to change it in the follosing way:
<div class="module m-slide">
<div class="m-slide-ctrl"></div>
<img src="http://placehold.it/1200x800&text=1" alt="" />
<img src="http://placehold.it/1200x800&text=2" alt="" />
<img src="http://placehold.it/1200x800&text=3" alt="" />
</div>
Demo
Related
I'm trying to get the value of the first child element from my HTML to show whenever I click on an image aka my 'services-cell" container, but it keeps saying the value is undefined.
<div class="services-cell">
<img class="services-cell_img" src="gallery/img-1.jpg" alt="">
<div class="services-cell_text">Digital Marketing</div>
</div>
Here is my Javascript
let galleryImages = document.querySelectorAll('.services-cell')
if(galleryImages) {
galleryImages.forEach(function(image){
image.onclick = function() {
console.log(galleryImages.firstElementChild.value)
}
})
}
I tried to add the img class as a variable as well, but it also says undefined. I want the console.log to print
<img class="services-cell_img" src="gallery/img-1.jpg" alt="">
I have multiple images with the same html except it just say img-2, img-3 etc. So ideally whenever I click on the other images it would print the same HTML value but just will say the image number that I clicked on
You created the array as galleryImages, but then rather than accessing the firstElementChild of the div, you're trying to access that property on the array. You need to do image.firstElementChild instead. Also, as far as I know, accessing .value of an image has no meaning, I think you meant to just do firstElementChild instead:
let galleryImages = document.querySelectorAll('.services-cell');
if (galleryImages) {
galleryImages.forEach(function (image) {
image.onclick = function() {
console.log(image.firstElementChild);
};
});
}
<div class="services-cell">
<img class="services-cell_img" src="https://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-12/256/deciduous-tree.png" alt="">
<div class="services-cell_text">Digital Marketing</div>
</div>
<div class="services-cell">
<img class="services-cell_img" src="https://cdn-cloudfront.cfauthx.com/binaries/content/gallery/gg-en-us/icons/gg-tree-icon.png" alt="">
<div class="services-cell_text">Digital Marketing</div>
</div>
What you could do to achieve this is passing the event attribute as a parameter of the onclick function.
The event attribute has a target; which is the item that triggered the event. So for example:
if(galleryImages) {
galleryImages.forEach(function(image){
image.onclick = function(e) {
console.log(e.target.firstElementChild.value)
}
})
}
However instead of adding an eventListener to every element, it might be better to add one event handler on the parent - and check which item is clicked.
E.g.
<div class="parent">
<div class="services-cell">
<img class="services-cell_img" src="gallery/img-1.jpg" alt="" />
<div class="services-cell_text">Digital Marketing</div>
</div>
<div class="services-cell">
<img class="services-cell_img" src="gallery/img-2.jpg" alt="" />
<div class="services-cell_text">Digital Marketing</div>
</div>
</div>
And the javascript:
document.querySelector('.parent').addEventListener('click', function(e){
if(e.target.matches('.services-cell'){
// Do something with the e.target - which is the .services.cell
}
}
I'm using jQuery to create a simple addClass on hover. Hovering over a #science-panel-number div triggers a class of .active to be added to an #iphone-screen-number div.
Here is my jQuery:
$('#science-panel-1').hover(function(){
$('#iphone-screen-1').addClass('active');
},function(){
$('#iphone-screen-1').removeClass('active');
});
$('#science-panel-2').hover(function(){
$('#iphone-screen-2').addClass('active');
},function(){
$('#iphone-screen-2').removeClass('active');
});
$('#science-panel-3').hover(function(){
$('#iphone-screen-3').addClass('active');
},function(){
$('#iphone-screen-3').removeClass('active');
});
My HTML:
<div class="col-md-4">
<div id="science-panel-1" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-2" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-3" class="science-panel__item">
Content goes in here!
</div>
</div>
<div class="col-md-4">
div id="iphone-screen-1" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
div id="iphone-screen-2" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-3" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-4" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-5" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-6" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
</div>
<div class="col-md-4">
<div id="science-panel-4" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-5" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-6" class="science-panel__item">
Content goes in here!
</div>
</div>
This feels like a lot of code to do the same script. Is there a way to have one piece of script that can add the numbers it self? As #science-panel-1 will always link to to #iphone-screen-1 and so on.
This will do what you need. Just apply the handlers to elements whose ID begins with science-panel-, which should cover all of them...
$("[id^=science-panel-]").hover(function() {
// get the corresponding iphone-screen element id
var iphoneScreen = "#" + this.id.replace("science-panel-", "iphone-screen-");
$(iphoneScreen).addClass("active");
},function() {
var iphoneScreen = "#" + this.id.replace("science-panel-", "iphone-screen-");
$(iphoneScreen).removeClass("active");
});
I recommend changing the markup to include the data you need to drive the script:
<div data-target="#iphone-screen-1" id="science-panel-1" class="science-panel__item">...</div>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This allows you to select all the science panel items at once:
$('.science-panel__item')
and perform the exact same script on each of them:
$('.science-panel__item').hover(function () {
$($(this).data('target')).addClass('active');
// ^^^^^^^^^^^^^^^^^^^^^^
// use the data-target attribute as a selector
}, function () {
$($(this).data('target')).removeClass('active');
});
If you change the attribute and the selector, you'll have a reusable feature you can apply to any element:
$('[data-hover-target]').hover(function () {
$($(this).data('hoverTarget')).addClass('active');
}, function () {
$($(this).data('hoverTarget')).removeClass('active');
});
I'd firstly ask if the active class is strictly necessary? Can what you want be achieved with CSS if it is for styling only by using the :hover pseudoclass?
If you do need the .active class for some reason, I would change the markup to be a little more generic so that all the science panels had a CSS class of .science-panel and all the iphone screens had a class of .iphone-screen. Then you could simplify the JS to look like
$('.science-panel').on('mouseenter mouseleave', function(e) {
$(this).find('.iphone-screen').toggleClass('active', e.type === 'mouseenter');
});
This will find the .iphone-screen inside of the .science-panel that you hover over and toggle the class to on if the mouse enters and off when the mouse leaves it.
edit: I see you've updated your answer to include your markup, this answer was assuming that your iphone-screens were nested in the science-panels so this won't necessarily work for you if you don't/can't nest your markup
I have following markup
var divs = $('div:has(img)').not(':parent:has(>img)');
divs.css('border','1px solid red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div><!-- get this div -->
1
<img alt='#' />
<div>
2
<img alt='#' />
<div>
3
<img alt='#' />
<div>
4
<img alt='#' />
</div>
</div>
</div>
</div>
<div><!-- get this div -->
5
<img alt='#' />
<div>
6
<img alt='#' />
</div>
<div>
7
<img alt='#' />
</div>
</div>
<div>
<div><!-- get this div -->
8
<img alt='#' />
</div>
</div>
From this I need to select the outermost div which contains img tag, that I don't want to select div if it's parent contains img tag as direct child. I have tried var divs = $('div:has(img)').not(':parent:has(>img)'); but it only works when it's have a parent.
Your main problem is the fact that :parent selector does not do what you think it does. CSS rules never go upwards. So if you need to go upwards, you need to do this using JavaScript (using the function .parent(), which does not have an equivalent in CSS selectors, not even jQuery extended ones).
var divs = $('div:has(>img)').filter(function(i, n) { return !($(n).parent().children('img').length); });
divs.css('color','red');
However, this will paint everything red, because of the first C in CSS ("cascading"): the declaration of colour red on 1, 5 and 8 will paint all text inside those divs red.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following structure:
<div class="container">
<img src="images/1.png" class="image_wall_thumbnail" />
<img src="images/2.png" class="image_wall_thumbnail" />
<img src="images/3.png" class="image_wall_thumbnail" />
<img src="images/4.png" class="image_wall_thumbnail" />
<img src="images/5.png" class="image_wall_thumbnail" />
<img src="images/6.png" class="image_wall_thumbnail" />
</div>
What I want to do is use the existing images I am using in the image tags and every 2-5 seconds I want to slowly fade one image and in it's place show another image (one of the existing images in the other image tags) and I want this effect to take place randomly.
I've never done this before so not sure how to go about this? I am thinking fade in and fade out makes sense but not sure how to tackle this. Any ideas?
Okay, so like any programming task you want to break something like this down into simple steps. In this case, maybe something like this:
When the page loads, only show the first image. To do this, you should have a display:none CSS rule on all of the images EXCEPT for the first one. This can easily be accomplished by created a class called hide and applying it to the HTML. We could also manage this via JS, but that may cause bugs depending on the internet connection that your users have...
Every five seconds, fade the current image out, and fade the next one in.
If we are on the last image, make sure we go back to the first image in the list.
That's pretty much all we need to do, so let's write some code:
First, let's refactor your markup to use an id for the container and then add the CSS class to all images but the first.
<div id="img_container">
<img src="images/1.png" class="image_wall_thumbnail" />
<img src="images/2.png" class="hide image_wall_thumbnail" />
<img src="images/3.png" class="hide image_wall_thumbnail" />
<img src="images/4.png" class="hide image_wall_thumbnail" />
<img src="images/5.png" class="hide image_wall_thumbnail" />
<img src="images/6.png" class="hide image_wall_thumbnail" />
</div>
Next, let's write a little CSS:
.hide {
display:none;
}
Okay now is the "tricky" part where we write some JS:
$(function() {
//cache dom elements and set init vars
var $img = $('#img_container').find('img'),
max = $img.length, //how many images you have in the container
current = 0; //we will start the script at the first item
//Every five seconds, run the code within the handler
setInterval(function(){
$($img[current]).fadeOut('fast', function(){
determineIndex(); //Update the index of the image in the img array
$($img[current]).fadeIn();
});
}, 5000);
function determineIndex () {
current = (current === max - 1) ? 0 : (current + 1);
}
});
Now here's the demo! http://jsfiddle.net/T2nzh/
Comment if you have any questions about how the javascript works. :)
EDIT: Okay, so if you want to just randomly swap out image sources, check this out. The html you want:
<div id="img_container">
<img src="images/1.png" style="background:red" class="image_wall_thumbnail" />
<img src="images/2.png" style="background:silver" class="image_wall_thumbnail" />
<img src="images/3.png" style="background:purple" class="image_wall_thumbnail" />
<img src="images/4.png" style="background:yellow" class="image_wall_thumbnail" />
<img src="images/5.png" style="background:green" class="image_wall_thumbnail" />
<img src="images/6.png" style="background:blue" class="image_wall_thumbnail" />
</div>
<div id="img_spares" style="display:none;">
<img src="images/7.png" style="background:magenta" class="image_wall_thumbnail" />
<img src="images/8.png" style="background:brown" class="image_wall_thumbnail" />
</div>
And the JS:
$(function() {
//cache dom elements and set init vars
var $img = $('#img_container'),
$spares = $('#img_spares'),
max = $img.find('img').length,
spares_max = $spares.find('img').length;
//Every five seconds, run the code within the handler
setInterval(function(){
$($img.find('img')[randomIndex(0,max)]).fadeOut('fast', function(){
var $el = $(this),
el_source = $el.attr('style'),
$swap = $($spares.find('img')[randomIndex(0,spares_max)]),
swap_source = $swap.attr('style');
$el.attr('style', swap_source).fadeIn();
$swap.attr('style', el_source);
});
}, 1000);
function randomIndex (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
});
And the demo: http://jsfiddle.net/T2nzh/3/
take a look:
<div class="container">
<img src="images/1.png" class="image_wall_thumbnail" />
<img src="images/2.png" class="image_wall_thumbnail" />
<img src="images/3.png" class="image_wall_thumbnail" />
<img src="images/4.png" class="image_wall_thumbnail" />
<img src="images/5.png" class="image_wall_thumbnail" />
<img src="images/6.png" class="image_wall_thumbnail" />
</div>
then the jQuery:
var slide = 1;
function slideshow() {
$("#container").find("img").animate({opacity:0});
setTimeout('$("#container").find("img").hide();',400);
setTimeout('$("#container").find("[src='images/"+slide+".png']").show();',400);
setTimeout('$("#container").find("[src='images/"+slide+".png']").animate({opacity:1});',400);
slide++;
}
var slideshow = setInterval("slideshow();",3000);
also, set the opacity to 0 and display to none for all the images. This code has not beenj tested so you might have to make some minor adjustments.
I have a bit of a problem I cant figure out.
I have a slideshow on my page using jquery.
<div id="carousel">
<div id="round">
<div class="box box-sec">
<img class="carousel-image" alt="Image Caption" src="_includes/images/carousel/sample1.jpg">
<div class="carousel-caption">
<p>
Peace of Mind <span>at the best rate possible...</span>
Click here for more
</p>
</div>
</div>
<div class="box box-easy">
<img class="carousel-image" alt="Image Caption" src="_includes/images/carousel/sample1.jpg">
<div class="carousel-caption">
<p>
Peace of Mind <span>at the best rate possible...</span>
Click here for more
</p>
</div>
</div>
<div class="box competitive">
<img class="carousel-image" alt="Image Caption" src="_includes/images/carousel/sample1.jpg">
<div class="carousel-caption">
<p>
Peace of Mind <span>at the best rate possible...</span>
Click here for more
</p>
</div>
</div>
<div class="box personal">
<img class="carousel-image" alt="Image Caption" src="_includes/images/carousel/sample1.jpg">
<div class="carousel-caption">
<p>
Peace of Mind <span>at the best rate possible...</span>
Click here for more
</p>
</div>
</div>
<div class="box business">
<img class="carousel-image" alt="Image Caption" src="_includes/images/carousel/sample1.jpg">
<div class="carousel-caption">
<p>
Peace of Mind <span>at the best rate possible...</span>
Click here for more
</p>
</div>
</div>
<div class="box affiliate">
<img class="carousel-image" alt="Image Caption" src="_includes/images/carousel/sample1.jpg">
<div class="carousel-caption">
<p>
Peace of Mind <span>at the best rate possible...</span>
Click here for more
</p>
</div>
</div>
<div class="arrows">
<div class="next"><span>Test</span><img src="_includes/images/icons/rarr.png" /></div>
<div class="prev"><span>Test</span><img src="_includes/images/icons/larr.png" /></div>
</div>
</div>
</div>
</div>
only 1 slide is active at a time, I want to somehow find the name of the next div, and write that into the "Test" span tags so that it shows up on hover and if clicked the span tag will then get the name of the next div and update itself, does this make sense? thanks
ADDED FIDDLE
http://jsfiddle.net/TNRMk/
Ive tried this with no luck
$('.arrows').click(function() {
$(".next span").html($('.roundabout-in-focus').next().attr('name'));
$(".prev span").html($('.roundabout-in-focus').prev().attr('name'));
});
Here is a good start for you:
$("div.arrows div").bind("mouseover", function() {
$("div.arrows div.next").children("span").text($("div.roundabout-in-focus").next("div").attr("class"));
$("div.arrows div.prev").children("span").text($("div.roundabout-in-focus").prev("div").attr("class"));
});
A number of points to be made:
This will not work for the prev arrow when the first item is selected.
I wasn't sure which part of the class name you wanted so you will need to do some modification
It needs to be on hover, or in the plugin itself as there are other ways to control the carousel. So setting on click won't work all the time.
The plugin provides callbacks btnNextCallback and btnPrevCallback that are executed after clicking the "next"/"prev" buttons are clicked.
The current focused item has the class .roundabout-in-focus.
I have made this jsfiddle for you to see (all you div have the same content so I've replaced it for the sake of the example).
Here's the (commented) code:
$(document).ready(function() {
function updatePrevNextTitle() {
// as this function is used as a callback for the plugin
// 'this' is the roundabout wrapper div
var $wrapper= $(this),
// get the currently focused div
$frontDiv = $wrapper.find('.roundabout-in-focus'),
// get the next/prev div content relative to the focused div
// also handle the circular roundabout by checking if
// .next() and .prev() return something, otherwise
// get .first() and .last()
nextContent = $frontDiv.next().length
? $frontDiv.next().find('.carousel-caption').html()
: $frontDiv.first().find('.carousel-caption').html(),
prevContent = $frontDiv.prev().length
? $frontDiv.prev().find('.carousel-caption').html()
: $frontDiv.last().find('.carousel-caption').html();
$wrapper.find('.next span').html(nextContent);
$wrapper.find('.prev span').html(prevContent);
};
$('#round').roundabout({
childSelector: 'div.box',
btnNext: ".next",
btnPrev: ".prev",
// set the method updatePrevNextTitle as the callback handler
btnNextCallback: updatePrevNextTitle,
btnPrevCallback: updatePrevNextTitle
}
// set it also as the 'initialized' callback for the
// initial setting of the prev/next span text
,updatePrevNextTitle);
});
One way is to add an active class in your selected div:
//e.g. after the selection event occurs:
$('div').click(function() {
$(this).addClass('active'); //keep track which div is clicked with the active class
//read the class name of the next sibling and store it in test (if i got it right)
$(".Test").html($('.active').next().attr('class'));
});
Maybe not 100% right but can give you a headstart!
According to your jsfiddle the name attribute is missing on your roundabouts,
try this instead:
$('.arrows').click(function() {
$(".next span").html($('.roundabout-in-focus').next().find('.carousel-caption').html());
$(".prev span").html($('.roundabout-in-focus').prev().find('.carousel-caption').html());
});