JQuery - click to show div then hide again - javascript

I have the following div, which is hidden:
<div class="showDescription 73" style="display:none;">blah blah blah</div>
and then at the side of it:
<div class="more" divtoshow="73" style="cursor:pointer">more...</div>
I want to click the div with class more and it shows the hidden div, then change the word more... to less..., remove class more, add a class canHide to it so when clicked again it will hide the div again. Simple stuff. It becomes this:
<div class="canHide" divtoshow="73" style="cursor:pointer">less...</div>
When i click the word more the hidden div shows and adds a class canHide, but when clicking it again nothing happens and I don't know why.
JQuery - this section works as it should:
$('.more').click(function() { // show hidden div
var classId = $(this).attr('divToShow');
$("." + classId).fadeIn();
$(this).removeClass('more');
$(this).addClass('canHide');
$(this).html('less...');
});
This section does nothing??
$('.canHide').click(function() { // hide shown div
var classId = $(this).attr('divToShow');
$("." + classId).fadeOut();
alert('hey'); // for test purposes only
$(this).removeClass('canHide');
$(this).addClass('more');
$(this).html('more...');
});
Here be a fiddle

You're changing the class, so that handler (which is bound at runtime), has no idea that that new class exists. Use event delegation:
$(document).on('click', '.canHide', function() { // hide shown div
});
document should be the element that contains the element with the .canHide class and is there at runtime, but since I can't see your HTML, document is a safe bet.

this might be easier
$('.more').click(function() {
// show/hide element before .more && toggle text
$(this).html($(this).html()=='▼'?'▲':'▼').prev('.showDescription').stop().fadeToggle();
});
It also removes the corresponding attributes between the more link and content, as it makes them unnecessary. ie divtoshow/class 73
made a fiddle: http://jsfiddle.net/filever10/zXz3c/
update: here's each piece broken down
$('.more').click(function() {
// get element
$(this)
//if html = ▼ then it should now be ▲, or if html = ▲ then it should now be ▼; else it should be ▼
.html($(this).html()=='▼'?'▲':'▼')
//get previous element by class
.prev('.showDescription')
//clear its queue to prevent buildup
.stop()
//fadeIn if it's hidden or fadeOut if it's visible
.fadeToggle();
});

Related

Execute function in this same element

I'm new here, and in Jquery ...
I am using Wordpress to create a website and I have a Jquery function for opening cards, these cards have a plus button, and clicking that button opens a description of the card ...
So far so ok, but all the cards have the same classes (on the button, and the description) and pulling it on the page I need to use them by clicking on one of the buttons it opens all the descriptions of the other cards ... can i make it open only the card description of the button i clicked?
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(this).ready(function(){
$(".abrir-btn").click(function(){
$(".conteudo-div").show(200);
$(".abrir-btn").hide();
$(".fechar-btn").show();
$(".listing-nucleados").css("background-color", "#FFE500");
$(".listing-nucleados").css("border-color", "#fff");
});
$(".fechar-btn").click(function(){
$(".conteudo-div").hide(200);
$(".abrir-btn").show();
$(".fechar-btn").hide();
$(".listing-nucleados").css("background-color", "#fff");
$(".listing-nucleados").css("border-color", "#EBEBEB");
});
});
</script>
Assuming, the buttons as well as the .listing-lucleados are both wrapped inside a parent element (let's call it .my-parent here). You can do the following:
$(this).ready(function(){
$(".abrir-btn").click(function(){
$(this).hide();
var parent = $(this).parents('.my-parent');
parent.find(".conteudo-div").show(200);
parent.find(".fechar-btn").show();
parent.find(".listing-nucleados").css("background-color", "#FFE500").css("border-color", "#fff");
});
$(".fechar-btn").click(function(){
$(this).hide();
var parent = $(this).parents('.my-parent');
parent.find(".conteudo-div").hide(200);
parent.find(".abrir-btn").show();
parent.find(".listing-nucleados").css("background-color", "#fff").css("border-color", "#EBEBEB");
});
});
Basically, what this does is going up the DOM tree to the parent element wrapping the show/hide buttons, as well as the list to show/hide. Then, from the parent element, find its descendants (I'm not saying direct children, because I do not know that much about your HTML structure) and apply the operation only to elements of this class inside the parent element.
In the function performed after clicking the button find a common ancestor of both elements - the button and the description - using closest().
Having an ancestor, find in it elements with the class .abrir-btn, .fechar-btn or .conteudo-div.
Example HTML:
<div class="content-outer">
<!-- the order inside is not important -->
<button class="abrir-btn" >show</button>
<button class="fechar-btn" >hide</button>
<div class="conteudo-div">...</div>
</div>
$(this).ready(function(){
$(".abrir-btn").click(function( event ){
var parent = $(event.target).closest(".content-outer");
if ( !parent.length )
return;
parent.find(".conteudo-div").show(200);
parent.find(".abrir-btn").hide();
parent.find(".fechar-btn").show();
parent.find(".listing-nucleados").css("background-color", "#FFE500").css("border-color", "#fff");
});
});

Append Div Class to Hyperlink Class — then Clone & Append Hyperlink To Container on Click

I want to append a div class ('.link-cloner') to a hyperlink class ('.link') when you hover over any hyperlink (that has the '.link' class).
Then when you click on the appended (.link-cloner) class, I want to clone the hyperlink it was appended to, and append that (link) to #container.
I'm almost there, I just can't make the last part work.
Codepen:
http://codepen.io/StrengthandFreedom/pen/JXEEQP/
I tried using find(), closest() & $(this) in various combinations, but I can't make it just clone the hyperlink (not the linkCloner) and append it to the #container.
jQuery:
$(document).ready(function(e) {
/* ------------------------
Part 1 — WORKS
--------------------------*/
// Store link-cloner div in variable
var linkCloner = $('<div class="link-cloner">Cloner</div>');
// When mouse hover over any hyperlink
$('.link').on('mouseover', function() {
// Append the link-cloner class to the hyperlink
$(this).append(linkCloner);
}).mouseleave(function() {
//on mouse leave, remove link-cloner
$(linkCloner).remove();
});
/* ------------------------
Part 2 — DOESN'T WORK
--------------------------*/
//Then when you click on the appended linkCloner,
clone the hyperlink and append it to the #container
$(linkCloner).on('click', function() {
// This code is wrong....
event.preventDefault();
$('.link').clone().append('<li></li>').appendTo('#container');
});
});
Can someone lead me in the right direction? JavaScript or jQuery, either is fine by me (I'm learning both) :-)
You have done just small mistake. Replace your PART 2 with below code :
$('.link').on('click', function(event) {
// This code is wrong....
event.preventDefault();
$(this).clone().append('<li></li>').appendTo('#container');
});
Try to use
$().drag();
for the clone that link to div check jquery documentations
Hope Help

Add class to element when second div has class

I have a Li element (dropdown) that gets an Active class when parent div (button) is clicked. When this element have this class I want to give another div the same class. When the li element (dropdown) is clicked again the active class is removed, I then want to remove the active class on the second div aswell.
What I got so far:
$('document').ready(function() {
if ($('li').hasClass('active')) {
$("#site-overlay").addClass("active");
}
});
This works a bit on the way in console- it gives my second div the correct class. It doesnt work live though, I guess I cant just call it on pageload? It also doesnt remove the class.
$('li').on('click', function(){
if($(this).hasClass('active')) {
$("#site-overlay").addClass("active");
} else {
$("#site-overlay").removeClass("active");
}
});
Your current example is not setting the active class on the LI elements, so nothing happens, but it should work something like this:
$(function () {
$('ul.megamenu > li').on('click', function () {
$("#site-overlay").toggleClass("active", $(this).hasClass('active'));
});
});
toggleClass can take a second boolean parameter that controls turning on/off the class based on a true/false value.
Note: I hacked the following JSFiddle just to show something working (the clicking just toggles the site-overlay state for now):
https://jsfiddle.net/TrueBlueAussie/doxdmxmL/16/

implement jquery show / hide toggles without accessing markup

I'm seeking a better way to rewrite a simple show / hide jQuery toggle that could allow implementation based on using div selectors; and without modifying HTML markup (so without added class .hidden etc)
I have a series of divs with class .djseform_field and no other selectors within; seeking to use only this class to turn these divs into show / hide jQuery toggles.
possibly something like this:
$(document).ready(function() {
// choose text for the show/hide link
var showText='read more...';
var hideText='hide';
// initialise the visibility check
var isVisible = false;
// append show/hide links to the element directly preceding the element with a class of "djseform_field"
$('.djseform_field').prev().append(' '+showText+'');
// hide all of the elements with a class of 'djseform_field'
$('.djseform_field').hide();
// capture clicks on the toggle links
$('a.toggleLink').click(function() {
// switch visibility
isVisible = !isVisible;
// change the link depending on whether the element is shown or hidden
if ($(this).html()==showText) {
$(this).html(hideText);
}
else {
$(this).html(showText);
}
// toggle the display
$(this).parent().next('.djseform_field').slideToggle('slow');
// return false so any link destination is not followed
return false;
});
});
Your jquery should look like :
$(document).ready(function() {
$('.toggle-div').click(function(){
$('.djseform_field').slideToggle( "slow", function() {
});
});
Your Html should :
<div class="djseform_field">111</div>
<div class="djseform_field">222</div>
<div class="djseform_field" >333</div>
toggle <!-- Whatever you want to on click hide / show divs for refs i used a tag -->

jQuery newsitems hide and collapse

I am using a nice script to hide and show several divs
// Catch all clicks on a link with the class 'link'
$('.link').click(function(e) {
// Stop the link being followed:
e.preventDefault();
// Get the div to be shown:
var content = $(this).attr('rel');
// Remove any active classes:
$('.active').removeClass('active');
// Add the 'active' class to this link:
$(this).addClass('active');
// Hide all the content:
$('.content').hide();
// Show the requested content:
$('#' + content).show();
});
This works great on a single div with several items I like to hide.
But I use a template the retrieves news items and I like to make this work on all the divs induvidual. Also hide the second div by default.
<div class="content" id="div[[+idx]]-1">
<p>Show content by default</p>
<a class="link-[[+idx]]" href="#" rel="div[[+idx]]-2">
Link to show div id="div[[+idx]]-2" and hide id="div[[+idx]]-1"
</a>
</div>
<div class="content hide" id="div[[+idx]]-2">
<p>Hide content by default</p>
<a class="link-[[+idx]]" href="#" rel="div[[+idx]]-1">
Link to show div id="div[[+idx]]-1" and hide div id="div[[+idx]]-2"
</a>
</div>
Problem is I use this template for every iteration and the script does not support an undefined number of items and closes all my other divs. As does the second div does not hide on default.
I changed the link to link1 and then you get the follwoing unwanted bahavior:
http://jsfiddle.net/Vh7HR/8/
if I leave out the 1 it does nothing
make use of .parent()
// Catch all clicks on a link with the class 'link'
$('.link').click(function(e) {
// Stop the link being followed:
e.preventDefault();
// Get the div to be shown:
var content = $(this).attr('rel');
// Remove any active classes:
$('.active').removeClass('active');
// Add the 'active' class to this link:
$(this).addClass('active');
// Hide all the content:
$(this).parent('.content').hide();
// Show the requested content:
$('#' + content).show();
});
You need to use delegation if you are adding new .link dynamically.
By using .on() you can listen for a click on document (or another element that is ancestor to .link and is present when the click handler is attached) and when the click is fired it will look for .link.
Try this:
$(document).on('click', '.link', function(e) {
I recommend you to use the on method provided by jquery to handle click events, the classic click method not works with elements that you create after rendering the DOM.
$( "your-selector" ).on( "click", function() {
alert( "Hello world!");
});

Categories

Resources