jquery show hide each div onclick - javascript

I have a dynamic number of divs which generated through asp.net. I need to show each div contents by clicking on its header. I have tried this {
$(function () {
var myHead = $(".toggle-container").find(".toggle-header");
var myBody = $(myHead).parent().find(".toggle-content");
$(myHead).click(function () {
if ($(myBody).css('display') === 'none') {
$(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
$(this).parent().find(".toggle-content").slideDown("slow");
} else if ($(myBody).css('display') === 'block') {
$(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
$(this).parent().find(".toggle-content").slideUp("slow");
};
});
});
But it's working only for first header and rest of the headers doesn't collapse it's children content. Here is the JsFiddle Link what I have tried so far. Can anyone give a fix?

The problem was how you were finding the content to be displayed/hidden. You need to find the content related to the clicked header you the code var myBody = $(myHead).parent().find(".toggle-content"); should go inside the click handler as var myBody = $(this).next()
$(function () {
var myHead = $(".toggle-container .toggle-header");
$(myHead).click(function () {
var myBody = $(this).next()
if ($(myBody).css('display') === 'none') {
$(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
$(this).parent().find(".toggle-content").slideDown("slow");
} else if ($(myBody).css('display') === 'block') {
$(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
$(this).parent().find(".toggle-content").slideUp("slow");
};
});
});
Demo: Fiddle
Note: Still the up-down arrows are nor working because you need to use find() instead of children()
But it can be simplified as
jQuery(function ($) {
var $heads = $(".toggle-container .toggle-header");
$heads.click(function () {
var $this = $(this);
$this.find('i').toggleClass('icon-chevron-sign-down icon-chevron-sign-up');
$this.next().slideToggle("slow");
});
});
Demo: Fiddle

The below would work.
In your original code you had assigned the variable myBody a value at the time of load itself. Since there are many such elements, it used only the first one.
Now I have moved the value setting for the myBody variable to be inside the click event and used $(this). This will make sure that it always finds the element in relation to the current element that was clicked.
$(function () {
var myHead = $(".toggle-container").find(".toggle-header");
$(myHead).click(function () {
var myBody = $(this).parent().find(".toggle-content");
//console.log('yes');
if ($(myBody).css('display') === 'none') {
$(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
$(this).parent().find(".toggle-content").slideDown("slow");
} else if ($(myBody).css('display') === 'block') {
$(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
$(this).parent().find(".toggle-content").slideUp("slow");
};
});
});
Fiddle Demo

Related

Transfer javascript to jQuery for the carousel

I am trying to convert the JavaScript to jQuery for my carousel.
The code I had is:
document.querySelectorAll('.indicators')[0].style.color = 'red';
document.querySelector('.toggler-prev').style.display = 'none';
document.addEventListener('postchange', function(event){
document.querySelectorAll('.indicators')[event.lastActiveIndex].style.color = 'white';
document.querySelectorAll('.indicators')[event.activeIndex].style.color = 'red';
var togglerPrev = document.querySelector('.toggler-prev');
var togglerNext = document.querySelector('.toggler-next');
if (event.activeIndex === 3) {
togglerPrev.style.display = 'block';
togglerNext.style.display = 'none';
} else if (event.activeIndex === 0) {
togglerNext.style.display = 'block';
togglerPrev.style.display = 'none';
} else {
togglerNext.style.display = 'block';
togglerPrev.style.display = 'block';
}
});
Which I transferred to jQuery:
$('.indicators').css('color','#000');
$('.toggler-prev').css('display','none');
$(window).on('postchange', function(event){
$('.indicators')[event.lastActiveIndex].css('color','#FFF');
$('.indicators')[event.activeIndex].css('color','#000');
var togglerPrev = $('.toggler-prev');
var togglerNext = $('.toggler-next');
if (event.activeIndex === 3) {
togglerPrev.css('display','block');
togglerNext.css('display','none');
} else if (event.activeIndex === 0) {
togglerNext.css('display','block');
togglerPrev.css('display','none');
} else {
togglerNext.css('display','block');
togglerPrev.css('display','block');
}
});
But it isn't working as I expected for example togglers are not being hidden and color of indicators not being changed.
This is the working JS example: http://codepen.io/anon/pen/eJYWQO
And my jQuery alternative: http://codepen.io/anon/pen/eJYWrq
Can anybody help me with editing my second codepen? Thanks in advance.
You forgot to mention somewhere that you are using AngularJS and onsenUI ;)
Your problem is, that the jQuery event does not have the properties activeIndex and lastActiveIndex, but they can be found in event.originalEvent.
Also, like #stalin said in his answer, your indicators are no jQuery objects, therefore you can't call the css-function on them. Wrap this stuff in another jQuery constructor like $() or even better, use the eq-function which returns a jQuery wrapped object from an array.
Then, to optimize some of the readability, you might want to consider the hide and show function instead of changing the CSS property display.
All in all your code should look like this
$('.indicators').css('color', '#fff');
$('.indicators').eq(0).css('color', '#000'); // highlight the first indicator
$('.toggler-prev').hide();
$(window).on('postchange', function(event) {
//store the indices for readability
var activeIndex = event.originalEvent.activeIndex;
var lastActiveIndex = event.originalEvent.lastActiveIndex;
$('.indicators').eq(lastActiveIndex).css('color', '#FFF');
$('.indicators').eq(activeIndex).css('color', '#000');
var togglerPrev = $('.toggler-prev');
var togglerNext = $('.toggler-next');
if (activeIndex === carousel.getCarouselItemCount() - 1) {
togglerPrev.show();
togglerNext.hide();
} else if (activeIndex === 0) {
togglerNext.show();
togglerPrev.hide();
} else {
togglerNext.show();
togglerPrev.show();
}
});
You have several problems in your implementation
First the event is not trigered in $(window) is in the $(document)
Your variable like lastActiveIndex are not in the event object are in event.originalEvent
$('.indicators')[event.lastActiveIndex] return a dom object not a jquery object you need to wrap this result in a jquery object to use the css() function
After you fix all this your code will work
Sorry that don't have time for create a fiddle for you :)

JavaScript changing image when hovering

I am trying to write a script, so that when someone hovers over an image, that same images changes to a different one, ie. I hover over up.png, and it changes to up_highlighted.png, when the mouse goes off the image it should change back.
However I can't seem to get it working despite all my attempts, here is the relevant code of what I have tried so far:
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up()\" onclick=\"increase_rating()\">";
function hover_up(){
$(document).ready(function() {
var oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').hover(function() {
//on hover of your element
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}, function() {
//when the cursor leaves your element
$('.thumbsbtn1').attr('src', oldSrc);
});
});
}
PS. I do not wish to use sprites.
Old School: http://jsfiddle.net/PAGUp/
var elem = document.getElementById('targetImg');
var oldSrc;
elem.onmouseover = function() {
oldSrc = elem.src;
elem.src = 'http://www.eclipse-developers.com/images/up_hover.png';
}
elem.onmouseout = function() {
if(typeof oldSrc !== 'undefined') {
elem.src = oldSrc;
}
}
I'm sure the jquery is more pithy. Essentially you need a variable to hold the 'old' src URL, and mouseover and mouseout handlers to set the new URL and back it out.
You don't have to wrap $(document).ready inside hover_up function. Note that I have removed onhover from HTML
Try
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onclick=\"increase_rating()\">";
$(document).ready(function() {
var oldSrc;
$(document).on('hover', '.thumbsbtn1', function () {
oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}, function () {
$('.thumbsbtn1').attr('src', oldSrc);
});
});
try this
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up(this)\" onclick=\"increase_rating()\" onmouseout=\"hover_out(this)\">";
var oldSrc;
function hover_up(e){
oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}
function hover_out(e){
$('.thumbsbtn1').attr('src',oldSrc);
}

javascript rotate what to change

I have ,
jQuery(function ($) {
var allArrows = $(".arrow"),
arrowUpUrl = "select_arrow_up.png",
arrowDownUrl = "select_arrow.png";
allArrows.click(function () {
var currentUrl = $(this).attr("src");
$(this).attr("src", currentUrl === arrowDownUrl ? arrowUpUrl : arrowDownUrl);
allArrows.not(this).attr("src", arrowDownUrl);
});
});
my problem is when I click outside arrow do not return first position what I must change ?
i can't use css and toggle whit jquery I need to use images with outside place
http://jsfiddle.net/cYCnD/9/
You should add the following handler:
$(document).on('click', function(e) {
if (!$(e.target).hasClass('arrow')) {
$('.arrow').attr('src', 'select_arrow.png');
}
});
See my fiddle: http://jsfiddle.net/cYCnD/10/
The whole code should look like this:
jQuery(function ($) {
var allArrows = $(".arrow"),
arrowUpUrl = "select_arrow_up.png",
arrowDownUrl = "select_arrow.png";
allArrows.click(function () {
var currentUrl = $(this).attr("src");
$(this).attr("src", currentUrl === arrowDownUrl ? arrowUpUrl : arrowDownUrl);
allArrows.not(this).attr("src", arrowDownUrl);
});
$(document).on('click', function(e) {
if (!$(e.target).hasClass('arrow')) {
allArrows.attr('src', 'select_arrow.png');
}
});
});
If I understand you correctly, you want to reset the arrows positions when a user clicks elsewhere on the page.
If so, I believe this will work:
$(document).click(function(e){
if(!$(e.target).hasClass('arrow'))
$(".arrow").attr("src", select_arrow.png)
});

get id of child element when parent is clicked

Hello I have seen similar posts but none answer what I want to accomplish
I made a sample here
http://jsfiddle.net/edgardo400/R6rVJ/
What i basically want is when a click happens in the parent you get the id of the child
and store it in a variable so i can pass the variable currentID to the code below otherwise I will have to replicate this code 9 times for each id from box1 to box9
jQuery(currentID).delegate("a", "hover", function(event){
var $img = jQuery(this).parent("li").find('img');
var image = jQuery(this).attr('data-img');
jQuery('.defaultimg').stop(true, true).fadeOut();
if( event.type === 'mouseenter' ) {
if($img.length){
$img.show();
}else{
jQuery(this).parent("li").append('<img id="theImg" src="' + image + '" />');
}
}else{
if($img){
$img.hide();
}
jQuery('.defaultimg').stop(true, true).fadeIn();
}
});
});
$('#boxes').on('click', function(e) {
var currentID = e.target.id;
console.log(currentID);
......rest of code
In javascript it would be:
var a = document.getElementById('#boxes');
a.onclick = function(e){
console.log(e.target.id);
}
If you only wish to make your code working and displaying on your console the box name, you should probably set
jQuery('#boxes').bind('click', function(event) {
var currentID = jQuery(event.srcElement).attr('id');
/* rest of your code */
});
You might want to do something easier
jQuery('#boxes').children().bind('click', function() {
jQuery(this).delegate...
});
Although I'm not sure why you are doing this ...
fixed http://jsfiddle.net/nxTDA/

make 'each' cycles occur consecutively

I have two actions I need to apply to a set of DIV's, but I need one cycle to happen before the other is finished.
Here is my code:
$("div").each(function(){
//do stuff first
}).each(function(){
//do stuff next
});
but at present, do stuff next happens before do stuff first finishes. Anything I can do to stop this?
Full Script
$("div").each(function(){
if($(this).html() === "yes"){
$(this).fadeOut(time,function(){
$(this).parent().height(0);
});
}
}).each(function(){
if($(this).html() !== "yes"){
$(this).parent().height(25);
$(this).fadeIn(time);
}
});
Knowing that you want to fadeIn and then set height, will this do what you require?
var divs = $('div');
divs.fadeIn(function () {
divs.height('200');
});
Using each to allow different settings for different divs:
$('div').each(function () {
var div = $(this), toggle = true;
div.fadeIn(function () {
if (toggle = !toggle) {
div.height('200');
} else {
div.width('200');
}
});
});
Seeing your code snippet I believe I got it now:
var yesDivs = $('div').filter(function () {
return $(this).html() === 'yes';
});
yesDivs.fadeOut(time, function () {
yesDivs.parent().height(0);
$('div').filter(function () {
return $(this).html() !== 'yes';
}).fadeIn(time).parent().height(25);
});

Categories

Resources