I have some collapsible panel divs that have a title attribute. When my jQuery opens the panel, I want the title attribute to change and I want to specify the div to change via the class of the panel currently being opened. i.e. this.div.class change title to "whatever".
To make the code stupid simple for your to follow:
<div class="panelContainer">
<div class="service">
<div class="serviceBrief" title="Click to Read More">
<p>Some Stuff for closed panel</p>
</div> <!-- end serviceBrief -->
<div class="serviceDescContainer">
<div class="serviceDesc">
<p>some more stuff that shows when panel is open</p>
</div><!-- end serviceDesc -->
</div><!-- end serviceDescContainer -->
</div><!-- end service -->
<div class="service">
<div class="serviceBrief" title="Click to Read More">
<p>Some Stuff for closed panel</p>
</div> <!-- end serviceBrief -->
<div class="serviceDescContainer">
<div class="serviceDesc">
<p>some more stuff that shows when panel is open</p>
</div><!-- end serviceDesc -->
</div><!-- end serviceDesc Container -->
</div><!-- end service -->
</div> <!-- end panelContainer -->
I understand how to do this using ID's
$('#sampleID').attr('title', 'Click to Read More');
But I want to do this referencing the div class to change the title attribute so when the panel is open the title="Click to Read Less"
I thought this would work:
$('.serviceBrief').attr('title', 'Click to Read Less');
and it does, but obviously it changes all instances of the title attribute instead of just the one that is open. I know I am missing making this a "this" type command in jQuery, but all my various attempts are failing and I can't for the life of me find a reference anywhere.
Can someone point me in the right direction? Thanks!
$(document).ready(function() {
$('.serviceBrief').each(function(){
$(this).append('<div class="panelOpenArrow"></div><div class="panelClosedArrow"></div>');
});
$('.serviceBrief').click(function(){
if ($(this).parent().is('.open')) {
$(this).closest('.service').find('.serviceDescContainer').animate({'height':'0'},500);
$(this).closest('.service').find('.panelOpenArrow').fadeOut(500);
$(this).closest('.service').find('.panelClosedArrow').animate({'height': '25px'});
$(this).closest('.service').removeClass('open');
}else{
var newHeight = $(this).closest('.service').find('.serviceDesc').height() + 'px';
$(this).closest('.service').find('.serviceDescContainer').animate({'height':newHeight},500);
$(this).closest('.service').find('.panelOpenArrow').fadeIn(500);
$(this).closest('.service').find('.panelClosedArrow').animate({'height':'0'});
$(this).closest('.service').addClass('open');
}
});
});
Why not just do:
$('.serviceBrief').click(function(){
if ($(this).parent().is('.open')) {
$(this).attr('title', 'Click to Read Less');
//rest of your code
You're right on the money. Just reference $(this) in your click event to apply the attribute to the clicked element, and not all .serviceBrief elements:
$('.serviceBrief').click(function(){
if ($(this).parent().is('.open')) {
$(this).attr( "title", "Click to Read Less");
$(this).closest('.service').find('.serviceDescContainer').animate({'height':'0'},500);
$(this).closest('.service').find('.panelOpenArrow').fadeOut(500);
$(this).closest('.service').find('.panelClosedArrow').animate({'height': '25px'});
$(this).closest('.service').removeClass('open');
}else{
var newHeight = $(this).closest('.service').find('.serviceDesc').height() + 'px';
$(this).attr( "title", "Click to Read More");
$(this).closest('.service').find('.serviceDescContainer').animate({'height':newHeight},500);
$(this).closest('.service').find('.panelOpenArrow').fadeIn(500);
$(this).closest('.service').find('.panelClosedArrow').animate({'height':'0'});
$(this).closest('.service').addClass('open');
}
});
You can pass your handler function a parameter e containing the event that triggered it. The e.currentTarget property will contain the actual element that is handling the event, so you can change the attribute of that to only affect the current element.
$('.serviceBrief').click(function(e){
var objThis = $(e.currentTarget);
var objService = objThis.parent();
if (objService.is('.open')) {
objService.find('.serviceDescContainer').animate({'height':'0'},500);
objService.find('.panelOpenArrow').fadeOut(500);
objService.find('.panelClosedArrow').animate({'height': '25px'});
objService.removeClass('open');
objThis.attr("title", "Click to Read More");
}else{
var newHeight = objService.find('.serviceDesc').height() + 'px';
objService.find('.serviceDescContainer').animate({'height':newHeight},500);
objService.find('.panelOpenArrow').fadeIn(500);
objService.find('.panelClosedArrow').animate({'height':'0'});
objService.addClass('open');
objThis.attr("title", "Click to Read Less");
}
});
Here is a fiddle: http://jsfiddle.net/gtXpx/
It's a good idea to cache your DOM queries in objects to improve performance.
You could write this all much easier. I'll shorten it "some", meaning there is even more beyond what I will show, but hopefully this breakdown will help you understand how powerful jQuery can really be.
Example
<script type="text/javascript">
$(function() { // same as $(document).ready ... but SHORTER!
$('.serviceBrief').each(function(i) { // of course i stands for the 0 based index of the elements in this object
$(this).append( // many different ways to (pre|ap)pend elemnts, this is my fav do to the "readability"
$('<div />', { class: 'panelArrow panelOpenArrow' }), // set attributes in the { }
$('<div />', { class: 'panelArrow panelClosedArrow' }) // don't forget to place comma before appending more elements
// keep in mind, you could continue inside here and append to what is being appended!
)
}) // here I continue to "chain", no need to recall the same object
.click(function(e) { // simple click event, you might also look at "delegate"ing events
var aroOpen = $(this).children('.panelOpenArrow'),
aroClose = $(this).children('.panelClosedArrow');
// i establish these variable for ease of use in next event
// considering the way your HTML is layed, there's really no need for all that "find"ing, it's just more code time, less action time!
$(this).next('.serviceDescContainer').slideToggle(500, function(e) { // this is much the same as what you were trying to do using .animate
if ($(this).is(':visible')) { // kind of like your class check, except this checks the display, opacity, and even considers height (in newer jQuery versions) for "visibility"
// at this point, this first line is "unneccesary", but I left it here in case you were doing some "CSS" using that class name
$(this).closest('.service').addClass('open');
// .stop prevents animations previously taking place, like if a user clicks this real fast
aroOpen.stop().fadeOut(500);
aroClose.stop().animate({ height: '25px' });
}
else {
$(this).closest('.service').removeClass('open');
aroOpen.stop().fadeIn(500);
aroClose.stop().animate({ height: 0 });
}
})
});
})
</script>
More Reading
How Does Chaining Work?
.ready()
.append()
learn to .delegate in jQuery 1.7+ with .on()!
.slideToggle()
Example with/out Comments
<script type="text/javascript">
$(function() {
$('.serviceBrief').each(function(i) {
$(this).append(
$('<div />', { class: 'panelArrow panelOpenArrow' }),
$('<div />', { class: 'panelArrow panelClosedArrow' })
)
})
.click(function(e) {
var aroOpen = $(this).children('.panelOpenArrow'),
aroClose = $(this).children('.panelClosedArrow');
$(this).next('.serviceDescContainer').slideToggle(500, function(e) {
if ($(this).is(':visible')) {
$(this).closest('.service').addClass('open');
aroOpen.stop().fadeOut(500);
aroClose.stop().animate({ height: '16px' });
}
else {
$(this).closest('.service').removeClass('open');
aroOpen.stop().fadeIn(500);
aroClose.stop().animate({ height: 0 });
}
})
});
})
</script>
Related
I'm appending some HTML to my button on a click, like this:
jQuery(document).ready(function($) {
$('#sprout-view-grant-access-button').on('click', function(e) {
$(this).toggleClass('request-help-cta-transition', 1000, 'easeOutSine');
var callback = $(e.currentTarget).attr('data-grant-access-callback');
var wrapper = $('.dynamic-container');
console.log(wrapper);
if( typeof window[callback] !== 'function') {
console.log('Callback not exist: %s', callback);
}
var already_exists = wrapper.find('.main-grant-access');
console.log(already_exists);
if( already_exists.length ) {
already_exists.remove();
}
var markup = $(window[callback](e.currentTarget));
wrapper.append(markup);
});
});
function generate_grant_access_container_markup() {
var contact_data_array = contact_data;
var template = jQuery('#template-sprout-grant-access-container')
return mustache(template.html(), {
test: 's'
});
}
As per the code, whatever comes from generate_grant_access_container_markup will be put inside dynamic-container and shown.
My problem is that, the newly added code just doesn't wanna dissapear upon clicking (toggle) of the button once again.
Here's my syntax / mustache template:
<script type="template/mustache" id="template-sprout-grant-access-container">
<p class="main-grant-access">{{{test}}}</p>
</script>
And here's the container:
<div class="button-nice request-help-cta" id="sprout-view-grant-access-button" data-grant-access-callback="generate_grant_access_container_markup">
Grant Devs Access
<div class="dynamic-container"></div>
</div>
I understand that the click event only knows about items that are in the DOM at the moment of the click, but how can I make it aware of everything that gets added after?
I would recommend visibility: hidden. Both display none and removing elements from the dom mess with the flow of the website. You can be sure you would not affect the design with visibility: hidden.
I don't deal with Jquery at all but it seems like this Stack overflow covers the method to set it up well.
Equivalent of jQuery .hide() to set visibility: hidden
I append the following content using jQuery to create a lightbox style popup that loads loads content using AJAX:
<div id="framebox-overlay">
<div id="framebox-wrapper">
<div id="framebox-nav-wrapper">
Previous
Next
</div>
<section id="framebox-content">
<!--AJAX to insert #single-project-wrapper content here-->
</section>
<div id="framebox-close">
<p>Click to close</p>
</div>
</div>
</div>
I am trying to get the appended next/previous links to work (.framebox-next and .framebox-prev as shown above), however the links are not triggering properly:
jQuery(document).ready(function(){
$('.framebox-trigger').click(function(e){
// Code that appends lightbox HTML and loads initial AJAX content goes here
});
// Code that isn't working:
$('body').on('click', 'a .framebox-next', function(e) {
e.preventDefault();
//remove and add selected class
var next = $('#portfolio-wrapper li.current-link').next('li > a');
$('#portfolio-wrapper li.current-link').removeClass('current-link');
$(next).addClass('current-link');
//fade out and fade in
var nexthref = $('#portfolio-wrapper li.current-link a').attr('href');
$('#single-page-wrapper').fadeOut('slow', function(){
var current = $('#portfolio-wrapper li.current-link a');
$(this).load(nexthref + " #single-page-wrapper", function(){
$(this).fadeIn('fast');
});
});
return false;
});
});
This last bit of code is not doing anything to the appended link .framebox-next. I have looked for other answers, and it seems that the .on() method should be effecting appended content.
Any help or input would be great.
Your selector is wrong for .framebox-next. You have a space between a and .framebox-next which would mean .framebox-next needs to be a child of the a element.
Use this selector instead:
$('body').on('click', 'a.framebox-next', function(e) {
...
}
Forgive the strangely worded question, my first StackOverflow post, and I'm a novice to jQuery/JS. I've used the search feature a lot and haven't found exactly what I'm looking for:
I am having an issue essentially, where I have dynamically added divs by the end-user (they pick how many content blocks they want to use), with the same class, that need to hide and show specific divs (with unique IDs) when they are clicked. I finally figured out how to give each div a unique ID, but I'm not sure how to get the child divs of the particular div what was clicked, to fire properly on click. Hope that makes sense.
Here is the HTML I have:
<div class="resource-video">
//Unique thumbnail
</div>
<div class="overlay-container hide" style="width: 50px; height: 50px;">
<div class="video-player hide">
//Included unique video
</div>
</div>
This will end up being duplicated based on how many videos are added.
Here is the JavaScript I am using:
//Generates unique IDs for each of the divs on the page with those classes
var i = 0;
$(".resource-video").each(function(i){
$(this).attr("id","video_"+ (i+ 1) );
});
$(".overlay-container").each(function(i){
$(this).attr("id","container_"+ (i+ 1) );
});
$(".video-player").each(function(i){
$(this).attr("id","player_"+ (i+ 1) );
});
//Currently opens all of them
$(".resource-video").on("click", function(){
openModal(".overlay-container", false, true);
alert($(this).attr("id")); //Alerts the right div clicked
if ($(".video-player").hasClass("hide")){
$(".video-player").removeClass("hide").addClass("show");
$(".overlay-container").animate({ height:'300px', width: '500px' }, "slow");
}
$("#overlay").on("click", function(){
$(".video-player").removeClass("show").addClass("hide");
$(".overlay-container").css({ "height":"50px", "width":"50px",
"display":"none"});
$(this).hide();
});
return false;
});
// Probably not totally necessary, but just in case
function closeModals(){
$("body").find(".modal").hide();
$("#overlay").hide();
$("body, html").removeClass("no-scroll");
};
function openModal(divID, allowScroll, blockScreen){
closeModals();
$(divID).show();
if ( blockScreen == true ){ $("#overlay").show(); };
if ( allowScroll == false ){ $("body, html").addClass("no-scroll"); };
};
As it stands now, all of the overlays open because I am targeting the class not the IDs. Basically, I need to find out a way to have the specific overlay associated with the specific div clicked on to display without hardcoding that, since the number of divs will change all the time. I would think I could use something like $(this) or event.target, but things I tried didn't work.
Hopefully I was clear enough with my issue and made it general enough for other people to use too. Thanks for any help in advance!
This uses DOM traversal functions to find the corresponding DIVs to the one that was clicked.
$(".resource-video").on("click", function(){
var overlayContainer = $(this).next();
var videoPlayer = overlayContainer.children(".video-player");
openModal(overlayContainer, false, true);
if (videoPlayer.hasClass("hide")){
videoPlayer.removeClass("hide").addClass("show");
overlayContainer.animate({ height:'300px', width: '500px' }, "slow");
}
return false;
});
// Only need to bind this once, not every time .resource-video is clicked.
$("#overlay").on("click", function(){
$(".video-player").removeClass("show").addClass("hide");
$(".overlay-container").css({ "height":"50px", "width":"50px",
"display":"none"});
$(this).hide();
});
// Probably not totally necessary, but just in case
function closeModals(){
$(".modal").hide();
$("#overlay").hide();
$("body, html").removeClass("no-scroll");
};
function openModal(div, allowScroll, blockScreen){
closeModals();
div.show();
if ( blockScreen == true ){ $("#overlay").show(); };
if ( allowScroll == false ){ $("body, html").addClass("no-scroll"); };
};
I just created script that shows/hides (toggles) block of HTML. There are four buttons that each can toggle its HTML block. When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button... it hides that HTML block and shows new one.
Here is what I have at the moment:
$('.btn_add_event').click( function() {
$('.block_link, .block_photos, .block_videos').hide();
$('.block_event').toggle();
});
$('.btn_add_link').click( function() {
$('.block_event, .block_photos, .block_videos').hide();
$('.block_link').toggle();
});
$('.btn_add_photos').click( function() {
$('.block_event, .block_link, .block_videos').hide();
$('.block_photos').toggle();
});
$('.btn_add_videos').click( function() {
$('.block_event, .block_link, .block_photos').hide();
$('.block_videos').toggle();
});
Any ideas how to reduce code size? Also, this script isn't very flexible. Imagine to add two new buttons and blocks.
like Sam said, I would use a class that all the blocks share, so you never have to alter that code. Secondly, you can try 'traversing' to the closest block, therefore avoiding it's name. That approach is better than hard coding each specific block, but if the html dom tree changes you will need to refactor. Last, but best, you can pass in the class name desired block as a variable to the function. Below is something you can copy paste that is close to what you started with.
$('.myAddButtonClass').click( function() {
$('.mySharedBlockClass').filter(':visible').hide();
//find a good way to 'traverse' to your desired block, or name it specifically for now.
//$(this).closest(".mySharedBlockClass").show() complete guess
$('.specificBlockClass').show();
});
I kept reading this "When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button" thinking that my eyes were failing me when Its just bad English.
If you want to make it more dynamic, what you can do is add a common class keyword. Then
when the click event is raise. You can have it loop though all the classes that have the
keyword and have it hide them all (except the current one that was clicked) and then show the current one by using the 'this' keyword.
you can refer below link,
http://chandreshmaheshwari.wordpress.com/2011/05/24/show-hide-div-content-using-jquery/
call function showSlidingDiv() onclick event and pass your button class dynamically.
This may be useful.
Thanks.
try this
$('input[type=button]').click( function() {
$('div[class^=block]').hide(); // I resumed html block is div
$(this).toggle();
});
Unfortunatly I couldn't test it, but if I can remember right following should work:
function toogleFunc(clickObject, toogleTarget, hideTarget)
{
$(clickObject).click(function()
{
$(hideTarget).hide();
$(toogleTarget).toggle();
});
}
And the call:
toogleFunc(
".btn_add_videos",
".block_videos",
".block_event, .block_link, .block_photos"
);
and so far
Assuming the buttons will only have one class each, something like this ought to work.
var classNames = [ 'btn_add_event', 'block_link', 'block_photos', 'block_videos' ];
var all = '.' + classNames.join(', .'); // generate a jquery format string for selection
$(all).click( function() {
var j = classNames.length;
while(j--){
if( this.className === classNames[j] ){
var others = classNames.splice(j, 1); // should leave all classes but the one on this button
$('.' + others.join(', .')).hide();
$('.' + classNames[j]).toggle();
}
}
}
All the buttons have the same handler. When the handler fires, it checks the sender for one of the classes in the list. If a class is found, it generates a jquery selection string from the remaining classes and hides them, and toggles the one found. You may have to do some checking to make sure the strings are generating correctly.
It depends by how your HTML is structured.
Supposing you've something like this
<div class="area">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
...
<div class="sender">
<a class="one"></a>
<a class="two"></a>
<a class="three"></a>
</div>
You have a class shared by the sender and the target.
Your js would be like this:
$('.sender > a').click(function() {
var target = $(this).attr('class');
$('.area > .' + target).show().siblings().hide();
});
You show your real target and hide its siblings, which aren't needed.
If you put the class postfixes in an array, you can easily make this code more dynamic. This code assumed that it doesn't matter in which order toggle or hide are called. If it does matter, you can just remember the right classname inside the (inner) loop, and toggle that class after the loop.
The advantage to this approach is that you can extend the array with an exta class without needing to modifying the rest of the code.
var classes = new Array('videos', 'event', 'link', 'photos');
for (var i = 0; i < classes.length; ++i)
{
$('.btn_add_' + classes[i]).click(
function()
{
for (var j = 0; j < classes.length; ++j)
{
if (this.hasClass('btn_add_' + classes[j]))
{
$('.block_' + classes[j]).toggle();
}
else
{
$('.block_' + classes[j]).hide();
}
}
});
}
You could make this code more elegant by not assigning those elements classes like btn_add_event, but give them two classes: btn_add and event, or even resort to giving them id's. My solution is based on your description of your current html.
Here is what I think is a nice flexible and performant function. It assumes you can contain your links and html blocks in a parent, but otherwise it uses closures to precalculate the elements involved, so a click is super-fast.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>
<script type="text/javascript">
// Enables show/hide functionality on click.
// The elements within 'container' matching the selector 'blocks' are hidden
// When elements within 'container' matching the selector 'clicker' are clicked
// their attribute with the name 'clickerAttr' is appended to the selector
// 'subject' to identify a target, usually one of the 'blocks'. All blocks
// except the target are hidden. The target is shown.
//
// Change clickerAttr from 'linkTarget' to 'id' if you want XHTML compliance
//
// container: grouping of related elements for which to enable this functionality
// clicker: selector to element type that when clicked triggers the show/hide functionality
// clickerAttr: name of the DOM attribute that will be used to adapt the 'subject' selector
// blocks: selector to the html blocks that will be shown or hidden when the clicker is clicked
// subject: root of the selector to be used to identify the one html block to be shown
//
function initToggle(container,clicker,clickerAttr,blocks,subject) {
$(container).each(
function(idx,instance) {
var containerElement = $(instance);
var containedBlocks = containerElement.find(blocks);
containerElement.find(clicker).each(function(idxC, instanceClicker) {
var tgtE = containerElement.find(subject+instanceClicker.getAttribute(clickerAttr));
var clickerBlocks = containedBlocks.not(tgtE);
$(instanceClicker).click(function(event) {
clickerBlocks.hide();
tgtE.toggle();
});
});
// initially cleared
containedBlocks.hide();
}
);
}
$(function() {
initToggle('.toggle','a.link','linkTarget','div.block','div.');
});
</script>
</head>
<body>
Example HTML block toggle:
<div class="toggle">
a <br />
b <br />
c <br />
<div class="A block"> A </div>
<div class="B block"> B </div>
<div class="C block"> C </div>
</div> <!-- toggle -->
This next one is not enabled, to show scoping.
<div class="toggle2">
a <br />
<div class="A block">A</div>
</div> <!-- toggle2 -->
This next one is enabled, to show use in multiple positions on a page, such as in a portlet library.
<div class="toggle">
a <br />
<div class="A block">A</div>
</div> <!-- toggle (2) -->
</body>
</html>
There was a fade out sample in the internet..
http://docs.dojocampus.org/dojo/fadeOut?t=tundra
but i want to do something different..
i want people directly click on the text then the text will fade out.
in my code there is a div wrap the text
<div id='parentNode'>
<div id='textDiv' onClick='whenClickAnyWhereWithinThisDiv_performFadeOut()'>
<div id='iconDiv'/>
<div id='messageDiv'/>
</div>
<div>
Code as show below, what i want is, when people click anywhere within the textDiv,
then the whole textDiv will fade away..hmm.....why my code doesn`t work???
function whenClickAnyWhereWithinThisDiv_performFadeOut () {
...
...
dojo.connect(dijit.byId('textDiv'), "onClick", fadeOutAndRemove(parentNode, textDiv));
}
function fadeOutAndRemove (parent, currentDiv) {
// just assume i can get the parent Node, and the current div, which will be textDiv
var objectId = currentDiv.getAttribute('id');
dojo.style(objectId, "opacity", "1");
var fadeArgs = {
node: objectId,
duration: 2000
};
dojo.fadeOut(fadeArgs).play();
setTimeout(function() { parent.removeChild(currentDiv);}, 2000);
}
If I understand what you are trying to do, I think you can accomplish it with this:
HTML
<div id='parentNode'>
<div id='textDiv'>
<div id='iconDiv'>this is icon div</div>
<div id='messageDiv'>this is message div</div>
</div>
<div>
JavaScript
// do it when the DOM is loaded
dojo.addOnLoad( function() {
// attach on click to id="textDiv"
dojo.query('#textDiv').onclick( function(evt) {
// 'this' is now the element clicked on (e.g. id="textDiv")
var el = this;
// set opacity
dojo.style(this, "opacity","1");
// do fade out
dojo.fadeOut({
node: this,
duration: 2000,
// pass in an onEnd function ref that'll get run at end of animation
onEnd: function() {
// get rid of it
dojo.query(el).orphan()
}
}).play()
});
});
The click will bubble up so it'll be caught by textDiv.
Here are some helpful links:
Dojo Animation quickstart
dojo.byId vs. dijit.byId
Let me know if I misunderstood your question and I'll update my answer. Hope this helps.