Dojo, how to do onclick event on a DIV - javascript

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.

Related

Programatically click on a div root to open the content that internally gets open using java scripts

I am trying to click on the div class (_2wP_Y) below programatically in order to open a part of the screen which display certain content using javascript internally.
<div class="_2wP_Y" style="z-index: 3; height: 72px; transform: translateY(72px);">
<div tabindex="-1">
<div class="_2EXPL CxUIE _1f1zm">
....
....
</div>
</div>
</div>
I tried various ways to click on HTMLDivElement object. Console log printing on website as clicked but on screen it doesn't get clicked automatically.
Codes I tried
var HTMLDivElement = document.getElementsByClassName('_2wP_Y')
HTMLDivElement.onclick = function() {
console.log("Clicked " );
}
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
HTMLDivElement.dispatchEvent(clickEvent);
It prints Clicked on console.
I also tried HTMLDivElement.click();
It also print Clicked on console, but click doesn't happen on browser.
There is multiple div having same class name(_2wP_Y) and I am using Chrome for testing in Ubuntu.
Basically I am trying to click on div on left side part of the image below to open the groups messages content in the middle of the section.
i hope this will work, happy coding :)
var HTMLDivElement = document.getElementsByClassName('_2wP_Y')
HTMLDivElement[0].addEventListener("onclick", function(){
console.log("clicked")
HTMLDivElement[0].style.backgroundColor = "red";
})
HTMLDivElement[0].dispatchEvent(new Event("onclick"));
<div class="_2wP_Y" style="z-index: 3; height: 72px; transform: translateY(72px);">
<div tabindex="-1">
<div class="_2EXPL CxUIE _1f1zm">
....
....
</div>
</div>
The problem could be that the dom is not yet loaded, resulting in the onclick event not really being attached to the DOM element. Another issue could be that getElementsByClassName returns an array and not a single element (like getElementById would). So if you only have one object with that particular class, you can just use HTMLDivElement[0]
Try to wrap everything within window.onload = function() {};:
window.onload = function() {
var HTMLDivElement = document.getElementsByClassName('_2wP_Y');
HTMLDivElement[0].onclick = function() {
console.log("Clicked");
}
}
Use jQuery.
//handling click event
$("._2wP_Y").click(function() {
alert("I was clicked");
})
//click itself
$("._2wP_Y").click();
<div class="_2wP_Y">i was clicked</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How can I hide a div that I've just added with a click?

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

How to change a div class title with jQuery

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>

Jquery show/hide div- minor tweak

I have the following javascript that shows or hides a div when a link is clicked:
<script type="text/javascript">
$(document).ready(function(){
$('.show_hide').showHide({
speed: 500, // speed you want the toggle to happen
changeText: 0, // if you dont want the button text to change, set this to 0
showText: 'View',// the button text to show when a div is closed
hideText: 'Close' // the button text to show when a div is open
});
});
(function ($) {
$.fn.showHide = function (options) {
//default vars for the plugin
var defaults = {
speed: 1000,
easing: '',
changeText: 0,
showText: 'Show',
hideText: 'Hide',
};
var options = $.extend(defaults, options);
$(this).click(function () {
// this var stores which button you've clicked
var toggleClick = $(this);
// this reads the rel attribute of the button to determine which div id to toggle
var toggleDiv = $(this).attr('rel');
// here we toggle show/hide the correct div at the right speed and using which easing effect
$(toggleDiv).slideToggle(options.speed, options.easing, function() {
// this only fires once the animation is completed
if(options.changeText==1){
$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
}
});
return false;
});
};
})(jQuery);
</script>
The problem is, I have two such divs, but I only want one to be displayed at a time. So, if someone clicks on the link to display div 2, and div 1 is already displayed, it should hide itself first before displaying div2.
Relevant HTML:
<div class="button">FAQs</div>
<div class="button">Contact</div>
<div id="faq" class="faq">FAQs here </div>
<div id="contact" class="faq">Contact form here </div>
I don't have any experience with JS/Jquery, but I tried adding this code, which didn't work:
var otherDiv;
if ($(this).attr('rel') == 'contact')
otherDiv = 'faq';
else
otherDiv = 'contact';
if ($(otherDiv).is(":visible"))
$(otherDiv).slideToggle(options.speed);
Most people use CSS classes as a place to store 'metadata'. When a div becomes visible, add a class to it like "toggledVisible" or whatever. When a new toggle is clicked, find all instances of "toggledVisible", hide them, and remove that class.
Alternatively, you always keep track of some sort of "currentlyVisible" object and toggle it.
Maybe jQuery ui accordion is an alternative?
HTML:
<div class="accordion">
<h3>FAQs</h3>
<div id="faq" class="faq">FAQs here</div>
<h3>Contact</h3>
<div id="contact" class="faq">Contact form here</div>
</div>
JS:
jQuery(document).ready(function() {
jQuery(".accordion").accordion();
});
Also see my jsfiddle.
=== UPDATE ===
JS:
jQuery(document).ready(function() {
jQuery(".accordion").accordion({
autoHeight: false
});
});
Also see my updated jsfiddle.
Try to add this row in your click() function
$('.faq').not(this).hide();
This will hide all shown divs except the one you clicked.

Jquery getting two divs to act as one

I have the following code for my popup menu, the parent link is the top level link. It causes a popup to show. Popup fades in and fades out when the mouse enters and exits parent link.
However, I need it to not fade out the popup, if the mouse is over the popup! At the moment, as soon as the mouse enters the popup it fades it out. I need both divs to act as one for the hover, if this makes any sense!
// Hovering over the parent <li>
ParentLink.hover(
function()
{
Popup.fadeIn(300, function() {
});
},
function()
{
Popup.fadeOut(400, function() {
});
}
);
You should nest the popup inside the parent. This way when you move the mouse from the parent to the popup, the parent will still be in a mouse-over state because popup's mouse-over event is bubbled onto the parent. When the mouse is out of the parent (plus its children), mouse-out event will fire on the parent.
Edit
If you are not able to (or want to) change the markup, one possibility is to move the elements to the recommended positions using jQuery, like:
ParentLink.append(Popup); // moves the Popup element from its current position
// and places it as the last child of ParentLink
Most probably you'll have to modify your CSS to match the changes so you may want to think first.
you could unbind the hover-event for the parentlink on completion of the fadein.
Popup.fadeIn(300, function() {
$(ParentLink).unbind('hover');
});
This is not a direct answer to your question but a hint how this could work.
Why don't you nest the the 2nd <div> into the first one, so the out will not occur?
<div id="ParentLink">
<div id="Popup"></div>
</div>
Have #ParentLink { display: relative; } and #Popup { display: absolute; } and you will be fine.
But for those menu's I would always use a nested unordered list structure like this one:
<ul id="topLevel">
<li id="level1item">
Link
<ul id="subLevel">
<li>
Link 2
</li>
</ul>
</li>
</ul>
As said, unbind the event while you are hover the popup and then re-bind it when you are hovering out :
ParentLink.hover(
handlerIn,
handlerOut
);
var handlerIn = function()
{
Popup.fadeIn(300, popupFadeIn);
};
var handlerOut = function()
{
Popup.fadeOut(400);
};
var popupFadeIn = function() {
$(ParentLink).unbind('hover');
$(this).mouseleave( function () {
$(ParentLink).hover(
handlerIn,
handlerOut
);
});
};
btw, I didn't tested this
You can try this:
var inn;
$('ParentLink').hover(function() {
inn = false;
$('p').fadeIn(1000);
},
function() {
$('Popup').bind('mouseenter mousemove',
function() {
inn = true;
}).mouseout(function() {
inn = false;
});
if (!inn) $('Popup').fadeOut(1000);
});

Categories