Timeout inside a function (javascript) - javascript

I've this code:
function divHideShow(divToHideOrShow)
{
var div = document.getElementById(divToHideOrShow);
if (div.style.display == "none")
{
div.style.display = "block";
}
else
{
div.style.display = "none";
}
}
How to make it wait 2 seconds when executing div.style.display = "block"; ?
Thanks

You can use the function setTimeout to wait for a specified time (in milliseconds) before running some code.
function divHideShow(divToHideOrShow)
{
var div = document.getElementById(divToHideOrShow);
if (div.style.display == "none")
{
setTimeout(function () {
div.style.display = "block";
}, 2000);
}
else
{
div.style.display = "none";
}
}
It might be worth considering adding and removing a class rather than setting the style directly. You can then handle all styles using CSS which helps with maintainability (and you can use CSS3 animations to fade/grow/shrink things in and out too).

This answers you question: the second parameter of setTimeout takes milliseconds so, 2000 milliseconds= 2 seconds
function divHideShow(divToHideOrShow)
{
var div = document.getElementById(divToHideOrShow);
if (div.style.display == "none")
{
setTimeout(function(){div.style.display = "block";},2000);
}
else
{
div.style.display = "none";
}
}
If you need fadeIn or fadeOut effects you better consider using jquery library:
You need to include jquery library in order this to be working.....
function divHideShow(divToHideOrShow)
{
var time=600; //milli seconds alter this for changing speed
$("#"+divToHideOrShow).fadeToggle(time);
}

Related

using javascript make button or link visible only on function call

I would like to add a button or link to appear on browser pop up window that makes a servlet request to get data. But the javascript that handles this should when an error occurs show the link or button on that window. Otherwise remain hidden.
function showErrorOnStart()
{
document.getElementById("video").innerHTML = "<p>This file is of
unsupported type. Please download the file</p>";
aud.style.visibility = "hidden";
vid.style.display = "none";
function myFunction() {
var x = document.getElementById("buttonLink");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
}
<button id="buttonLink" type="button"
style="display:none;" onclick="myFunction()">DownLoad</button>
I have no idea what I'm doing and would like someone to guide me to get this done correctly. Basically this function is called when an error occurs and displays a suitable message, but this time I want to include a link/button that this window will display which a user can then click and it will return a video stream.
PROTIP: As I always say to newbies, indentation is a must. Your code is bad indented and things like that can lead to code misunderstanding, hence to errors.
As far as I can tell, you code is fine BUT when I clean your indentation, you have one function defined inside another function:
function showErrorOnStart() {
document.getElementById("video").innerHTML = "<p>This file is of unsupported type. Please download the file</p>";
aud.style.visibility = "hidden";
vid.style.display = "none";
function myFunction() {
var x = document.getElementById("buttonLink");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
}
This is a perfect example of why good indentation is a must.
The scope where myFunction can be reached is showErrorOnStart contents, so anything outside showErrorOnStart can't access myFunction. You must define it outside:
function showErrorOnStart() {
document.getElementById("video").innerHTML = "<p>This file is of unsupported type. Please download the file</p>";
aud.style.visibility = "hidden";
vid.style.display = "none";
}
function myFunction() {
var x = document.getElementById("buttonLink");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
With this it should work as expected (as long as where you define the function is the global scope, not inside another function).

JQuery cookie set in other Function

I had a javascript Function showHide(shID) , which is a function to hide div or show content after clicked "read more" . Here is my Fiddle : http://jsfiddle.net/Garfrey/5xf72j4m/8/
As you see when user click on it and show more content , but I just need to hide once , means when the user come back to visit my page and the hidden content is still showing. So that I need to add JQuery cookie , but what I wrote was wrong and it's not working .I'am new in Javascript . Do anyone know how to fix it ? thanks in advance , I really need help .
here my code for function :
<script language="javascript" type="text/javascript">
jQuery(document).ready(function(){
if($.cookie("example")=='1') {
function showHide(shID) {
if (document.getElementById(shID+'-show').style.display != 'none') {
document.getElementById(shID+'-show').style.display = 'none';
document.getElementById(shID).style.display = 'block';
}
else {
document.getElementById(shID+'-show').style.display = 'inline';
document.getElementById(shID).style.display = 'none';
}
}
} else {
$.cookie("example", "1");
}
});
</script>
You can't define a function inside jQuery's ready function without doing something like this
var showHide;
$(function() { // Document ready
showHide = function(sh) {
//Insert function code here
};
});
I think in your case you might be better off defining the function outside of the ready function then binding it to the button's onclick handler dynamically.
I also added a data-showhide attribute to the button to pass the variable into the showhide function onclick.
function showHide() {
var shID = $(this).data("showhide"); // Use lower case only in data
if (document.getElementById(shID + '-show').style.display != 'none') {
document.getElementById(shID + '-show').style.display = 'none';
document.getElementById(shID).style.display = 'block';
} else {
document.getElementById(shID + '-show').style.display = 'inline';
document.getElementById(shID).style.display = 'none';
}
}
$(function() {
$("#example-show").on("click", showHide);
});
<a href="#" id="example-show" class="showLink" data-showhide="example">
The cookies can be set to specific values in the showHide function. The ready handler can then query the cookie and determine whether or not to show or hide the div.
This fiddle shows this in action http://jsfiddle.net/e52hxosb/19/

Show/Hide Function(s)

Fixed Solution
//Hide and Show Divs
function hideContent(d) {
document.getElementById(d).style.display = "none";
}
function showInlineContent(d) {
document.getElementById(d).style.display = "inline";
}
function showBlockContent(d) {
document.getElementById(d).style.display = "block";
}
function reverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}
//Hide and Show Divs
// Show Div Click to show.
function researchStick() {
if (stick >= 1 && research1Progress < 100) { // Want to be able to show progress
stick = stick - 1; // each time you click me I want to use 1 stick
research1Progress = research1Progress + 5; // each stick brings research progress up 5
document.getElementById("stick").innerHTML = stick; // Show the player the update
}
if (research1Progress == 100) { // When reaches 100
showInlineContent('crafting2'); // show crafting2
}
// when research hits 100 unlocks blunt object for crafting
// this clickable button should hide after completion
// add achievement for first research project
}
Here is the fixed solution after applying some fixes. being able to call more then one if function is helpful to know, especially since all the tutorials I took did not specifically indicate it otherwise. maybe is was meant to be obvious but knowing this has helped me a newcomer to java create more code on my own

Javascript show more/ show less with speed effect

i have this javascript code:
<script language="javascript" type="text/javascript">
function showHide(shID) {
if (document.getElementById(shID)) {
if (document.getElementById(shID+'-show').style.display != 'none') {
document.getElementById(shID+'-show').style.display = 'none';
document.getElementById(shID).style.display = 'block';
}
else {
document.getElementById(shID+'-show').style.display = 'inline';
document.getElementById(shID).style.display = 'none';
}
}
}
</script>
it is possible to add a toggle speed effect for show and hide?
Adding Effect to you code will result you to add more code line for Browsers Compatibility.
I suggest you to use jQuery, It will save you lot of time developing and testing.

Making a show/hide smaller

How would I make this code smaller? Maybe a toggle, but people were saying this was easily done in jQuery. But the problem is that I am not a fan of using jQuery for just one thing in my code.
function open() {
document.getElementById('message').style.display='block';
document.getElementById('fade').style.display='block';
}
function close() {
document.getElementById('message').style.display='none';
document.getElementById('fade').style.display='none';
}
DRY it up.
var b='block',h='none',m='message',f='fade';
function s(i,d){document.getElementById(i).style.display=d}
function open(){s(m,b);s(f,b)}
function close(){s(m,h);s(f,h)}
With the whitespace and proper variable names (to be passed to a minifier), this looks like:
var show = 'block', hide = 'none', message = 'message', fade = 'fade';
function setStyle(id, display) {
document.getElementById(id).style.display=display;
}
function open() {
setStyle(message, show);
setStyle(fade, show);
}
function close() {
setStyle(message, hide);
setStyle(fade, hide);
}
There are some best-practices which don't relate to the question but are worth considering if your project grows beyond this trivial situation:
Use a minifier. My favorite is uglifyjs. This allows you to use meaningful variable names in your unminified code (like the second example). The minifier will output code more like (but probably even better than) the first example. Even with a minifier, keep thinking about what it can and cannot do - creating a private shortcut to a long public API like document.getElementById can aid the minification if you use that API frequently. Look at the minified code to make sure there isn't something you can do to optimize it.
Separate your javascript into .js modules that are loaded separate from the page and asychrounously, if possible.
Manage all your static assets (like the .js modules) so they have a long cache timeout - use the Expires: http header. Then change their URLs when they actually change. This way, clients can cache them indefinitely until you change them & then the client will immediately fetch a new version.
Put discrete modules inside function wrappers, so that your variables don't conflict with other pieces of code - either your own or 3rd party modules. If you want to make a variable public, do it explicitly: window.pubvar =
var message = document.getElementById('message'),
fade = document.getElementById('fade');
function open() {
message.style.display = fade.style.display = 'block';
}
function close() {
message.style.display = fade.style.display = 'none';
}
Or:
function toggle() {
var message = document.getElementById('message'),
fade = document.getElementById('fade'),
currentdisplay = getComputedStyle(message, null)['display'];
if(currentdisplay == 'block' || currentdisplay == 'inline')
message.style.display = fade.style.display = 'none';
else
message.style.display = fade.style.display = 'block'; /* or inline */
}
Or:
function toggle() {
var currentdisplay = getComputedStyle(arguments[1], null)['display'],
i,
newdisplay;
if(currentdisplay == 'block' || currentdisplay == 'inline')
newdisplay = 'none';
else
newdisplay = 'block';
for(i = 0; i < arguments.length; i++)
arguments[i].style.display = newdisplay;
}
var message = document.getElementById('message'),
fade = document.getElementById('fade');
toggle(message, fade); /* hide */
toggle(message, fade); /* show */
document.body.onclick = function(){
toggle(message, fade);
}
​
Toggle Example:
http://jsfiddle.net/djHTq/
var toggle = function(doc){
var $ = doc.getElementById, message = $('message'), fade = $('fade'), open = true;
return function(){
var display = open ? 'none' : 'block';
message.style.display = display;
fade.style.display = display;
open = !open;
}
}(document);
toggle(); // Hide both elements
toggle(); // Show both elements. Rinse and repeat.
Avoids polluting global scope:
(function() {
var msgstl = document.getElementById('message').style,
fdestl = document.getElementById('fade').style;
window.open = function() {msgstl.display = fdestl.display = "block";};
window.close = function() {msgstl.display = fdestl.display = "none";};
})();
One thing is you can create a helper function for setting styles on elements. This would be useful in cases where you need to set many different elements.
function setStyle(element, style, value) {
document.getElementById(element).style[style] = value;
}
function open() {
setStyle('message', 'display', 'block');
setStyle('fade', 'display', 'block');
}
function close() {
setStyle('message', 'display', 'none');
setStyle('fade', 'display', 'none');
}
You may also want to set the elements to variables if you work with the elements often enough.
var message = document.getElementById('message'), fade = ...

Categories