scriptaculous blindUp/blindDown issue - javascript

I wrote a little script that observes clicks and blinds up/down according to the 'display' property, and also added a queue-to-end parameter to the blindUp in order to avoid even more serious display issues. This is obviously not the way to implement this, as display bugs appear if click events are invoked in the middle of the effect.. This is the code:
<script type="text/javascript">
$$('#leftnav_container #modules h2').each(function(El){
El.observe('click',function(){
container = this.next('div');
display = container.getStyle('display');
if(display == 'none'){
container.blindDown({duration: 0.3});
}else{
container.blindUp({duration: 0.3, queue: 'end'});
}
})
});
</script>
Again, the problem is that I rely on 'display'. What is the proper way to this?

This should simplify it
$$('#leftnav_container #modules h2').invoke('observe','click',function(){
container = this.next('div');
Effect.toggle(container , 'blind', { duration: 0.3 });
});
Firstly if you are only running one method on all elements in the array returned from $$() then you can use the PrototypeJS method invoke().
http://api.prototypejs.org/language/Enumerable/prototype/invoke/
Then Effect.toggle() will check if the element is visible and do the appropriate up/down effect.
Try this out and let me know if it works for you.

Related

How to toggle jQuery element with a duration AND display?

When I want to toggle off a component I can use
$("#donkey").toggle(false);
and when I need it to be toggled during a certain time period I can use
$("#emailInvalid").toggle(700);
but now I'd like to combine those two. I want to ensure that the component is being toggled off (not only toggled back and forth) and I want to specify a duration of the process.
According to the jQuery API, I'm supposed to be able to specify an object with options, too. However, the following
$("#donkey").toggle({ duration: 700, display: false });
only toggles the donkey back and forth (during said time, though), whereas I'd like it to be toggled to invisibility. When I reviewed the options, I noticed that there's none that addresses display, so I fear that the above is treated by jQuery equivalently with
$("#donkey").toggle({ duration: 700, biteMe: "in the donkey" });
How can I make sure that the toggler is hiding the component (equivalent with the first line of code above) and that I can control the time for the process to be done (equivalent to the second line of code above)?
Apply toggle only when visible:
$('#donkey:visible').toggle(500);
Alternatively
var element=$('#donkey');
if(element.css('display') !== 'none'){
element.toggle(500);
}
Short answer - you can't.
Your options are to build something custom and carry out the logic in custom code. Alernatively, you might want to toggle between differen classes that have the look that you like. Check out toggleAss() for details.
For completeness I also give you a link to animate() as suggested by #DavidThomas, although I haven't used that one very much.
I think this is what you want -- if the element (#donkey) is visible it gets hidden, if it's hidden nothing happens.
$( '#button' ).click( function(){
if( $( '#donkey' ).css( 'display' ) === 'block' ) {
$("#donkey").toggle( 700 );
}
});
Codepen: http://s.codepen.io/SteveClason/debug/RRwpBd
This small plugin would allow you to combine the two:
(function ( $ ) {
$.fn.myToggle = function(show, options) {
return this.each(function() {
if ($(this).is(":hidden") ? show : !show) $(this).toggle(options);
});
};
}( jQuery ));
Simple example:
$("#donkey").myToggle(false, 700);

Element with hidden css not changing with javascript .show()

I have a dropdown list that I am hiding on initialization since it's not needed unless the client actually selections a specific radiobuttonlist object. I'm presently setting it to false through
dlInterval.Attributes.CssStyle[HtmlTextWriterStyle.Visibility] = "hidden";
However, attempting to change this through javascript on selection, is failing, at present, I have my code set up to execute as such.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#<%=rblVectorChoices.ClientID%>").click(function() {
var intVectorSelectedIndex = $('#<%=rblVectorChoices.ClientID %> input[type=radio]:checked').val();
$("#<%=dlInterval.ClientID %>").style.visibility="visible";
if (intVectorSelectedIndex == 1) {
$("#<%=dlInterval.ClientID%>").show();
} else {
$("#<%=dlInterval.ClientID%>").hide();
}
});
});
</script>
As you can see I'm currently attempting to change the visibility from hidden, back to visible, yet I am receiving an error in the browser console 'TypeError: Cannot set property 'visibility' of undefined'
This doesn't make much sense to me, as the field should be hidden, and not just null. What is causing this to happen, and what is a good solution for such a thing?
The HTML attribute is not called visibility.
In CSS the corresponding attribute for .show() / .hide() is display.
the code you were looking for is :
dlInterval.Attributes.CssStyle["display"] = "none";
or you can just change the javascript to look like, I personally would think that you should hide the element in javascript if your going to show it in javascript . Instead of setting the display:none; in .Net code that is going to disappear when the page is rendered
just re-write your code like this:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
// hide element initially
$("#<%=dlInterval.ClientID%>").hide();
$("#<%=rblVectorChoices.ClientID%>").click(function() {
// much easier way to check if check box is checked
if ( $("#<%=rblVectorChoices.ClientID input[type=radio]:checked%>").is(":checked)) {
$("#<%=dlInterval.ClientID%>").show();
} else {
$("#<%=dlInterval.ClientID%>").hide();
}
});
});
</script>
also , I strongly , strongly reccomend using classes to select your html elements with javascript or jquery , .Net mangles the id's and you have to write out this weird syntax to get the proper id, uses classes prevents all that
NOTE: if you're going to use this second example then you never need to mess with
dlInterval.Attributes.CssStyle["display"] = "none";
Can you use prop and compare if it's true or false? Also, you cant call $("#<%=dlInterval.ClientID %>").style.visibility="visible"; you have to call it this way:
For those of you reminiscing on the missing .NET inline ID's here's my modified code:
$(document).ready(function () {
$("#<%=rblVectorChoices.ClientID%>").click(function () {
var intVectorSelectedIndex = $('#<%=rblVectorChoices.ClientID%>').prop('checked');
$("#<%=dlInterval.ClientID%>").css('visibility', 'visible');
if (intVectorSelectedIndex == true) {
$("#<%=dlInterval.ClientID%>").show();
} else {
$("#<%=dlInterval.ClientID%>").hide();
}
});

Menu items - onclick FadeInDown and FadeOutUp

I have a menu composed of three options.
Clicking on one causes a container div to "FadeInDown".
Then, its contents "FadeIn".
Clicking on another menu item or anywhere else on the page causes the
contents to "FadeOut" then container div to "FadeOutUp".
Here is the fiddle that I have been testing jsfiddle
$(document).ready(function() {
$('.container').each(function() {
animationHover(this,'.fadeInDown');
});
});
I'm not very familiar with jQuery and have been trying to use animate-css to get me along. Thanks for any help and tips in advance and welcome coding criticism :)
My answer is mainly based on JQuery and its animate function (http://api.jquery.com/animate/) . Here is the fiddle :
http://jsfiddle.net/awmat/7/
I use JavaScript objects like fadeInDown to animate the container.
var fadeInDown = {
opacity:1,
top: "50px"
};
And i use the complete callback function of animate to make the content appear after the container.
To manage several div (one for each menu item), I use id as selectors, but since the "click and display" function remains the same, I used a "builder" : (this uses a closure, so if you're not familiar with JavaScript, you may have to read several times to understand what is going on)
var menuClickCallbackBuilder = function(menuItem){
var container = $('#container' + menuItem);
var content = container.find('.content');
var showContent = function(){
content.animate({opacity:1},{duration:1000});
};
return function() {
var activeContainer = $('.active');
var hideContainer = function(){
activeContainer.animate(fadeOutUp,1000);
};
activeContainer.find('.content').animate({opacity:0},{duration: 1000, complete : hideContainer});
activeContainer.removeClass("active");
if(activeContainer[0] != container[0])
{
var timeout = activeContainer[0] ? 2000 : 0 ;
setTimeout(function(){
container.animate(fadeInDown,{duration : 1000, complete :showContent});
},timeout);
container.addClass("active");
}
}
};
This way, when you add the add the click callbacks, you can just do :
$(document).ready(function(){
// note that menuClickCallbackBuilder(1) returns a function
// again if you're not familiar with JS, you may have to re-read menuClickCallbackBuilder
$('#menuLink1').on('click', menuClickCallbackBuilder(1));
$('#menuLink2').on('click', menuClickCallbackBuilder(2));
$('#menuLink3').on('click', menuClickCallbackBuilder(3));
});
Some improvements you can bring to this :
Factor the durations into a variable (e.g animationDurationInSeconds) so that if you want to change the speed of the animation, you only have 1 thing to change. (#Huangism: and right after you did that, make animation faster so that it gets more dynamic)
(From #Huangism) : stop it from going crazy when people cicks on the menu 10 times really fast
Actually, I think you don't need 3 different containers, you could do it with just one container (though I don't know if it would be considered an improvement)
There is probably a way to use CSS classes instead of fadeInDown and fadeOutUp JS objects. That would be cleaner, I think you should keep styles in CSS as much as you can.
There is no need for different IDs for menu items, you could do the exact same thing with a loop.
Whatever your imagination wants to add

force DOM redraw with javascript on demand

The title of the question expresses what I think is the ultimate question behind my particular case.
My case:
Inside a click handler, I want to make an image visible (a 'loading' animation) right before a busy function starts. Then I want to make it invisible again after the function has completed.
Instead of what I expected I realize that the image never becomes visible. I guess that this is due to the browser waiting for the handler to end, before it can do any redrawing (I am sure there are good performance reasons for that).
The code (also in this fiddle: http://jsfiddle.net/JLmh4/2/)
html:
<img id="kitty" src="http://placekitten.com/50/50" style="display:none">
<div>click to see the cat </div>
js:
$(document).ready(function(){
$('#enlace').click(function(){
var kitty = $('#kitty');
kitty.css('display','block');
// see: http://unixpapa.com/js/sleep.html
function sleepStupidly(usec)
{
var endtime= new Date().getTime() + usec;
while (new Date().getTime() < endtime)
;
}
// simulates bussy proccess, calling some function...
sleepStupidly(4000);
// when this triggers the img style do refresh!
// but not before
alert('now you do see it');
kitty.css('display','none');
});
});
I have added the alert call right after the sleepStupidly function to show that in that moment of rest, the browser does redraw, but not before. I innocently expected it to redraw right after setting the 'display' to 'block';
For the record, I have also tried appending html tags, or swapping css classes, instead of the image showing and hiding in this code. Same result.
After all my research I think that what I would need is the ability to force the browser to redraw and stop every other thing until then.
Is it possible? Is it possible in a crossbrowser way? Some plugin I wasn't able to find maybe...?
I thought that maybe something like 'jquery css callback' (as in this question: In JQuery, Is it possible to get callback function after setting new css rule?) would do the trick ... but that doesn't exist.
I have also tried to separte the showing, function call and hiding in different handlers for the same event ... but nothing. Also adding a setTimeout to delay the execution of the function (as recommended here: Force DOM refresh in JavaScript).
Thanks and I hope it also helps others.
javier
EDIT (after setting my preferred answer):
Just to further explain why I selected the window.setTimeout strategy.
In my real use case I have realized that in order to give the browser time enough to redraw the page, I had to give it about 1000 milliseconds (much more than the 50 for the fiddle example). This I believe is due to a deeper DOM tree (in fact, unnecessarily deep).
The setTimeout let approach lets you do that.
Use JQuery show and hide callbacks (or other way to display something like fadeIn/fadeOut).
http://jsfiddle.net/JLmh4/3/
$(document).ready(function () {
$('#enlace').click(function () {
var kitty = $('#kitty');
// see: http://unixpapa.com/js/sleep.html
function sleepStupidly(usec) {
var endtime = new Date().getTime() + usec;
while (new Date().getTime() < endtime);
}
kitty.show(function () {
// simulates bussy proccess, calling some function...
sleepStupidly(4000);
// when this triggers the img style do refresh!
// but not before
alert('now you do see it');
kitty.hide();
});
});
});
Use window.setTimeout() with some short unnoticeable delay to run slow function:
$(document).ready(function() {
$('#enlace').click(function() {
showImage();
window.setTimeout(function() {
sleepStupidly(4000);
alert('now you do see it');
hideImage();
}, 50);
});
});
Live demo
To force redraw, you can use offsetHeight or getComputedStyle().
var foo = window.getComputedStyle(el, null);
or
var bar = el.offsetHeight;
"el" being a DOM element
I do not know if this works in your case (as I have not tested it), but when manipulating CSS with JavaScript/jQuery it is sometimes necessary to force redrawing of a specific element to make changes take effect.
This is done by simply requesting a CSS property.
In your case, I would try putting a kitty.position().left; before the function call prior to messing with setTimeout.
What worked for me is setting the following:
$(element).css('display','none');
After that you can do whatever you want, and eventually you want to do:
$(element).css('display','block');

Trigger event on animation complete (no control over animation)

I've a scenario that requires me to detect animation stop of a periodically animated element and trigger a function. I've no control over the element's animation. The animation can be dynamic so I can't use clever setTimeout.
Long Story
The simplified form of the problem is that I'm using a third party jQuery sliding banners plugin that uses some obfuscated JavaScript to slide banners in and out. I'm in need of figuring out a hook on slideComplete sort of event, but all I have is an element id. Take this jsfiddle as an example and imagine that the javascript has been obfuscated. I need to trigger a function when the red box reaches the extremes and stops.
I'm aware of the :animated pseudo selector but I think it will need me to constantly poll the required element. I've gone through this, this, and this, but no avail. I've checked jquery promise but I couldn't figure out to use that in this scenario. This SO question is closest to my requirements but it has no answers.
P.S. Some more information that might be helpful:
The element isn't created by JavaScript, it is present on page load.
I've control over when to apply the plugin (that makes it periodically sliding banner) on the element
Most of the slideshow plugins I have used use changing classes at the end of the animation... You could extend the "addClass" method of jQuery to allow you to capture the class change as long as the plugin you use is using that method like it should:
(function($){
$.each(["addClass","removeClass"],function(i,methodname){
var oldmethod = $.fn[methodname];
$.fn[methodname] = function(){
oldmethod.apply( this, arguments );
this.trigger(methodname+"change");
return this;
}
});
})(jQuery);
I threw together a fiddle here
Even with obfuscated code you should be able to use this method to check how they are sending in the arguments to animate (I use the "options" object when I send arguments to animate usually) and wrap their callback function in an anonymous function that triggers an event...
like this fiddle
Here is the relevant block of script:
(function($){
$.each(["animate"],function(i,methodname){
var oldmethod = $.fn[methodname];
$.fn[methodname] = function(){
var args=arguments;
that=this;
var oldcall=args[2];
args[2]=function(){
oldcall();
console.log("slideFinish");
}
oldmethod.apply( this, args );
return this;
}
});
})(jQuery);
Well since you didn't give any indication as to what kind of animation is being done, I'm going to assume that its a horizontal/vertical translation, although I think this could be applied to other effects as well. Because I don't know how the animation is being accomplished, a setInterval evaluation would be the only way I can guess at how to do this.
var prevPos = 0;
var isAnimating = setInterval(function(){
if($(YOUROBJECT).css('top') == prevPos){
//logic here
}
else{
prevPos = $(YOUROBJECT).css('top');
}
},500);
That will evaluate the vertical position of the object every .5 seconds, and if the current vertical position is equal to the one taken .5 seconds ago, it will assume that animation has stopped and you can execute some code.
edit --
just noticed your jsfiddle had a horizontal translation, so the code for your jsfiddle is here http://jsfiddle.net/wZbNA/3/

Categories