Jquery open and close within a parent div - javascript

The title does not explain that well, essentially I have 8 divs the same, with the same class for css styling.
They all have hidden content, I want to be able to only expand one div at a time without using different classes or identifiers for each div and hidden content.
I have tried to display this on Jsfidle using two divs the same , however I can't even get it to fire on jsfiddle for some reason
http://jsfiddle.net/dAXJ2/8/
$(document).on('click',".servicereadmore",function() {
//var x = $(this).closest('div').attr('class')
//$('.hiddenservices').parent(x).slideDown(1000);
$('.hiddenservices').slideDown(1000);
$(this).html("Read less");
$(this).removeClass("servicereadmore");
$(this).addClass("servicereadless");
});
$(document).on('click', ".servicereadless" ,function() {
$('.hiddenservices').slideUp(1000);
$(this).html("Read more");
$(this).removeClass("servicereadless");
$(this).addClass("servicereadmore");
});
That currently works above but opens all the hidden text as stated, the comments are were I have been trying to only expand within the parent div of the button I pressed

Your clickable <a> tags should probably be buttons, since that's the role they're in. Also, your functions aren't working currently because you've added
return false;
as the first statement of each one. That prevents any of the code after that from ever running. Instead of that, either change those <a> links to <button type=button> or else add a parameter to the handlers ("e" or "event") and call
e.preventDefault();
in the handler.
To affect only the portion of the page relevant to the "Read More" links, you just need to navigate the DOM:
$(this).closest('.myinfo').find('.hiddenservices').slideDown(1000);
That means: "staring from the clicked element, climb up the DOM to find the closest element with class 'myinfo', and then from that point down find all the elements with class 'hiddenservices' and slide them down."
A couple of other problems: you'll need to start the "hiddenservices" sections off as hidden, or otherwise not visible somehow. Also, another issue with your jsfiddle was that you didn't have jQuery selected. That's something you could quickly learn just by checking the error console.
Here is a repaired jsfiddle.

You dont have to use that much of code for this purpose. USe simply like
$(document).on('click', ".servicereadmore", function (e) {
e.preventDefault();
if ($(this).parent().find('.hiddenservices').is(":visible")) {
$(this).html("Read more");
} else {
$(this).html("Read less");
}
$(this).parent().find('.hiddenservices').slideToggle(1000);
});
Instead of adding and removing the class name, you can just use slideToggle().
Demo

Related

onclick dropdown menu with a form, click outside to close

ive got a drop down menu with form elements. the menu element gets set to
display:none
when anything outside the element is clicked ... or at least so i thought.
Here's my little function
$(function(){
$('#loginAcc').click( function(event){
event.stopPropagation();
//show
$('#auth-menu').css('display', 'block');
});
$(document).click( function(){
//hide when click anywhere out the menu
$('#auth-menu').hide();
});
})
the problem i have is that it also closes when i click inside the element, which makes it very difficult, pretty much impossible to complete a form.
#loginAcc
is a horizontal list item that gets clicked, and
#auth-menu
is
if i were to hazard a guess, i would like to think that .toggle() is the culprit, but that's a sheer guess and i wouldn't even know where to start if i were to reimplement it (a little bird told me that it's getting taken out of the spec anyway).
what i would like to happen is that when you click on the #loginAcc list item, the #auth-menu gets set to display:block, and can only be closed if you reclick #loginAcc or anywhere else outside of #auth-menu.
any help would be amazing. thanks
Use a not() selector to exclude the menu:
$(document).not('#auth-menu').click( function(){
//hide when click anywhere out the menu
$('#auth-menu').hide();
});

How to perform: onClick Javascript, hide a div with transition effect

This is a question that is related to a previous question of another member which can be found here.
This is the Javascript function to hide a div (which is an answer to the other member's question):
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
The HTML is:
<div id='hideme'>
Warning: These are new products
<a href='#' class='close_notification' title='Click to Close'>
<img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" />
</a>
</div>
My followup question to this is: how can I add a cool effect of transition? The result will be the div 'hideme' would close slowly. Is there a work around for this?
Thanks so much everyone! It would be highly appreciated!
Note: I'm a noob with Javascript. 0-0
$("#"+el).fadeOut(500);//el must be the id of the element
If you're using jQuery
function hide() {
$(this).parent().fadeOut();
}
As this is triggered by an event the 'this' variable will be set to the element from which it came, as you want the parent element to vanish when it's clicked this will do the trick
EDIT: For this to work you may have to play with your HTML and how many $(this).parent().parent()... you need but this would be the best way to go about it, then you don't need to pass the ID around
EDIT 2: So .parent() selects the element containing the selected element, so in this case $(this) refers to the button that was clicked as that's where the click event came from.
So $(this).parent() refers to the container element, in this case the a element and therefore the $(this).parent().parent() refers to the div element which you want to hide.
So you could give the image a class of 'closable' then do the following
$('.closable').click(function() {
$(this).parent().parent().fadeOut();
}
This means whenever you click something with the class closable it will go up the DOM tree two elements to (with .parent().parent()) and then fade it out.
This will allow you to remove the on click event from the image, you just need to put the handler above in the jQuery document.ready function which looks like:
$(document).ready(function() {
//Click function here
});
A popular choice for this would be JQuery UI's effect method.
With this, you can write some very simple Javascript to hide your div in a stylish manner, for example:
function hide(obj) {
$(obj).effect("scale");
}
EDIT:
Here's an example jsFiddle
Use jQuery to do transition effects:
$(function(){
$("a.close_notification").click(function(e){
e.preventDefault();
// stop other animations and hide, 500 milliseconds
// you can use the function fadeOut for that too
$("#hideme").stop().hide(500);
});
});

Add DISPLAY: NONE to span via jQuery when: mouse-click outside span, OR click EXIT button, etc+

What I want is really simple, but every time I try to add the functionality I want, the more I'd mess things up, so I decided to ask help and stick with the working basic script I have now.
I already have a script in progress, that I would like to develop to work almost exactly like this:
https://stackoverflow.com/a/7133084/1399030 { http://jsfiddle.net/Paulpro/YpeeR/25/ } (by: PaulP.R.O.)
Open a hidden span
Hide a hidden span
Span has "CLOSE" button to exit span
Hide currently opened span when another span is triggered
Think... Image Gallery Preview functionality... Kind of.
"Preview" spans are triggered when either .popCover or a.thumbnail is clicked on the webpage, this hidden span will appear based on its specified unique id, by jQuery inserting display: block; to its css.
This is inside a loop with multiple items.
I've gotten this far and this is the working script that I use:
$(document).ready(function() {
$('.popCover').click(function(){
divID = $(this).attr('id');
$("#tooltip-"+divID).fadeIn('5000', function() {
$("#tooltip-"+divID).css("display", "block");
});
});
$("a.thumbnail").click(function() {
dvID = $(this).attr('id');
$("#tooltip-"+dvID).fadeIn('5000', function() {
$("#tooltip-"+dvID).css("display", "block");
});
});
});
But now, I need to add to these functions the trigger to make the span disappear again, (by inserting display: none; to its css.
I'd want the CURRENT SPAN to disappear when:
01. Mouse click is made outside of the span element
02. An exit or X button is clicked INSIDE the span. (like on image galleries, when they preview an image, and exit it by either clicking outside the element or an exit button provided within the preview)
03. .popCover or a.thumbnail is re-clicked (probably to trigger another span of a different ID to show.)
NOTES:
Currently, I can click as many anchors on the page and all these spans with different IDs just accumulate and stack up over each other on the page.
I don't really want that. I don't want more than 1 span to be open at one time, so I was hoping to add functionality that would make the current opened span exit itself when another anchor click is made.
I really did try to do this myself, but... I can't get the methods I've tried to work. It was too complicated to add all these functions together since I'm no jQuery expert. I could get one to work and then ruin it by trying to work in another.
Also, I was thinking of using this similar way of exiting the span:
$(".the_span").fadeOut("5000").css("display", "none");
The only reason I'm not willing to just use some plugin and uncomplicate things for me is, I already really like my "Preview" span css, I have it all ready. I just need the jquery part to work:
To display: block a span when triggered, and display: none it if mentioned conditions are met.
Hoping for assistance, and will be very grateful for each single one! Thank you.
You have to try to add a class on the opened / active element and then bind all the events to close it. Binds have to be done on elements with class .active for example, when closed, .active class have to be removed.
I've finally gotten this to work! :o)
By using if ($("span.the_span").is(":visible")) to check if span with class="the_span" was currently visible / open / or has display: block in its CSS, and if so, to:
- hide the currently open span, before proceeding to show the new span. -
Here's my working finished product that addresses all the functionality I wanted:
$(document).ready(function() {
// When clicks on either ".popCover" or "a.thumbnail" is made,
// Funcion clickPOP is triggered:
var clickPOP = function() {
divID = $(this).attr('id');
// Checks if "span.the_span" is already currently open:
if ($("span.the_span").is(":visible")) {
$("span.the_span").css("display", "none"); // If open, this is where it closes it..
$("#tooltip-"+divID).fadeIn('200', function() { // Then, proceeds to open the new clicked span here.
$("span.the_span #tooltip-"+divID).css("display", "block"); });
}
// But if no "span.the_span" is currently open:
// No need to close anything, it will directly open the new span...
else {
$("#tooltip-"+divID).fadeIn('5000', function() {
$("span.the_span #tooltip-"+divID).css("display", "block"); });
}
} // End of Function. Added functionality starts below...
// Exits "span.the_span" when mouse clicks outside of element
// ... ("Outside of element" means: outside of "span.the_span")
$(document).click(function(){
$("span.the_span").css("display", "none");
});
// Exit Button : Exits "span.the_span" when exit button is clicked
$('span.exitme').css('cursor', 'pointer').click(function(e){
$("span.the_span").css("display", "none");
e.stopPropagation();
});
// This makes sure that clicks inside "span.the_span" continue to work
$('span.the_span').click(function(e){
e.stopPropagation();
});
// This makes sure that clicks on ".popCover" continue to work
$(".popCover").click(function(e){
e.stopPropagation();
});
// This makes sure that clicks on "a.thumbnail" continue to work
$("a.thumbnail").click(function(e){
e.stopPropagation();
});
// Clicks on both ".popCover" & "a.thumbnail"
// ... will trigger actions specified on function: clickPOP.
$(".popCover").click(clickPOP);
$("a.thumbnail").click(clickPOP);
});
As you can see, I've also added the $(document).click(function() etc. to get my original desired functionality of hiding the span when mouse clicks outside of the element, but making sure that clicks can still be made if they are done on .popCover (div) or a.thumbnail (link) on the webpage.
Also, I wouldn't have been able to complete writing this method without the tips from these posts:
* Running same function / different triggers: https://stackoverflow.com/a/1191837/1399030
* Fix clicking inside element (including exit button): https://stackoverflow.com/a/4660691/1399030
* How to check if something is hidden or visible: https://stackoverflow.com/a/178450/1399030
I especially found the last post VERY helpful (and basically it made me understand what I was doing), because poster: Tsvetomir Tsonev included in his code comments:
// Checks for display:[none|block], ignores visible:[true|false]"
I didn't really initially understand that jQuery was able to check or connect with CSS that wasn't inline (being a jQuery noob myself), so that post was indeed very enlightening.
Of course, if there is a better, more efficient way to do this, I would be very happy to be enlightened some more! jQuery is still a learning curve for me, and I'm a very eager student!

Advice on how to update navigation code to hide and show hidden div

I currently have a list with one particular link that hides/shows a hidden div. As a link is clicked the class 'active' is removed and added and the hidden div checked to see whether it is visible or hidden and hidden/shown accordingly. This all works ok, but, there is one problem. When I click Square I want to show the #square but when I click it again I want to hide the #square but because Im checking for the .active this cant be done. Can anyone offer any suggestions on how I can update the code so this can be achieved?
JS
$(document).ready(function(){
var square = $('#square'),
test = $('#test');
square.hide();
test.find('a').on('click', function(e){
if( !$(this).hasClass('active') ){
if ( square.is(':visible') ){
square.hide();
}
var id = $(this).data('id');
test.find('a').removeClass('active');
$(this).addClass('active');
if( id === 'square' ){
square.show();
}
}
e.preventDefault();
});
});​
HTML
<ul id="test">
<li>Triangle</li>
<li>Square</li>
<li>Circle</li>
</ul>
<div id="square"></div>​
Fiddle: http://jsfiddle.net/xBuUY/
I made a fork of your Fiddle.
I've moved the block for testing whether the square should be visible or not outside of checking which link should be active. The #square is toggled and not only shown which garanties that it's hidden when it's already active. Just test the Fiddle.
Apart from that I optimized the event-handler: It now uses delegation, which is faster than just the link handler on each of the links. Bubbling of the links is prevented by e.stopPropagation(). I've added this before any other methods or anything else is called for performance reasons.
Move this block of code --
if ( square.is(':visible') ){
square.hide();
}
outside of the hasClass('active') check.
Your logic can be simplified, you're wanting to toggle square regardless of class, so I've removed the square toggle outside of the class test. Try this Fiddle HERE

Do I have to duplicate this function? - jQuery

I'm using this function to create an transparent overlay of information over the current div for a web-based mobile app.
Background: using jQTouch, so I have separate divs, not individual pages loading new.
$(document).ready(function() {
$('.infoBtn').click(function() {
$('#overlay').toggleFade(400);
return false;
});
});
Understanding that JS will run sequentially when i click the button on the first div the function works fine. When I go to the next div if I click the same button nothing "happens" when this div is displayed, but if i go back to the first div it has actually triggered it on this page.
So I logically duplicated the function and changed the CSS selector names and it works for both.
But do I have to do this for each use? Is there a way to use the same selectors, but load the different content in each variation?
Would something like this work? I'm assuming what you want is for different buttons to call toggleFade on different overlay divs.
function makeOverlayHandler(selector) {
return function() {
$(selector).toggleFade(400);
return false;
}
}
$('button selector').click(makeOverlayHandler('#overlay1'));
$('another button selector').click(makeOverlayHandler('#overlay2'));
You could also change makeOverlayHandler's selector parameter to a jQuery object instead of a selector and call it like this: makeOverlayHandler($('#overlay1')).
This best way to do this is to make it all relative, so say you have markup like this:
<div class="container">
<div class="overlay">Overlay content</div>
<button class="infoBtn">Click to show overlay</button>
</div>
Then you can find the overlay for this button realtively, like this:
$(function() { //equivalent to $(document).ready(function() {
$('.infoBtn').click(function() {
$(this).closest('.container').find('.overlay').toggleFade(400);
return false;
});
});
You can optimize this further, e.g. .children('.overlay') if the overlay is always a direct child of container. This goes from the current button (this), finds the .container it's in using .closest() and then finds the .overlay inside of it using .find(). With this approach you have one small bit of code to handle all your bindings, much easier to maintain :)

Categories

Resources