Collapsing JavaScript/HTML div on page load? - javascript

I need help collapsing a collapsible div on page load.
I'm using this JavaScript code:
<script type="text/javascript">
function switchMenu(obj) {
var el = document.getElementById(obj);
if ( el.style.display != "none" ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
}
document.getElementById('aboutme').style.display = 'none';
</script>
to collapse HTML div id="aboutme" when the <a ...>about me</a> is clicked:
<div class="container">
about me
<div id="aboutme">
sample text to be expanded and collapsed
</div>
</div>
I can't get the page to close my div#aboutme on page load.
I want this page to load with my div collapsed.
I thought that the JS line
document.getElementById('aboutme').style.display = 'none';
should do the trick but it doesn't. What am I doing wrong?
Thanks for your help.

If you want your div to load collapsed, simply write the following
<div id="aboutme" style="display:none">
sample text to be expanded and collapsed
</div>
This should resolve the problem.
However, if you are still interested in the JavaScript solution keep reading.
As you said I can't get the page to close my div#aboutme on page load - the problem is that you are not using "onload" event.
Simply put the line document.getElementById('aboutme').style.display = 'none'; in your body's onload attribute..
something like this
<body onload="document.getElementById('aboutme').style.display = 'none';">
...
</body>
and you should see the results with JavaScript. I recommend you use "style" method instead. much better.

Exactly how do you make that JS run on window load? It may simply run before the page is rendered
Does clicking on the link work? if it does, that would prove that the issue is simply the loading sequence
The easiest solution would be to place your code at the very end of your HTML file, just before the closing </body> tag. The code below is more generic, and can be placed anywhere. Note that to toggle the link back on I set the display to 'inline' (or block, i.e. whatever it was before - you may want to save that to a variable to be sure)
<script type="text/javascript">
function switchMenu(id) {
var el = document.getElementById(id);
if ( el.style.display != "none" ) {
el.style.display = 'none';
}
else {
el.style.display = 'inline'; //or block - i.e. whatever it is rendered by
}
}
//add to the window onload event
if( window.addEventListener ){
window.addEventListener( 'load', function(){ switchMenu('aboutme')}, false);
} else if (window.attachEvent) {
window.attachEvent("onload", function(){ switchMenu('aboutme') } );
}
</script>

Related

Show/Hide Div using JS

I'm working on a personal website and I'm trying to have a show/hide on click of an image, but I'm not really sure where the problem is.
HTML
<div id="menuopen">
<a href="#" onclick="toggle('menu');">
<img src="assets/Images/menu.gif" alt="Menu">
</a>
</div>
<div id="menu">
<ul>
<li>Home</li>
<li>Home</li>
<li>Home</li>
<li>Home</li>
</ul>
</div>
JS
<script type="text/javascript">
<!--
function toggle(id) {
var item = document.getElementById(id);
if(item.style.display == 'block')
item.style.display = 'none';
else
item.style.display = 'block'; }
//-->
As a side note, this script also did not work using plain text rather than the image, so I don't think that my problem lies there.
Sometimes the style properties are empty/meaningless until they have been set in JavaScript. You can either set the value in JS first or you can have your JS assume the starting state.
Solution 1 - Set state from JS:
var s = document.getElementById('menu').style;
s.display = 'block';
function toggle() {
if(s.display == 'block') { s.display = 'none'; }
else { s.display = 'block'; }
}
Solution 2 - Assume unset means it's visible
function toggle(id) {
var s = document.getElementById('menu').style;
s.display = (s.display!=='block' ? 'block' : 'none');
}
Check this one. Just a short explanation, your function is checking if the element has a block value attached to it's display property which is wrong - by default this property is empty. So, rather ask for none or an empty (default) value.
function toggle(o) {
var e = document.getElementById(o);
e.style.display = (e.style.display != 'none' ? 'none' : '' );
}
I don't have a lot of time to analyze, but I'd recommend using an in-body function with a click trigger instead of pre-defining the function. Something like what's in the fiddle here :
fiddle
Hope this helps, let me know if you want some clarification and I'll do what I can.

Toggle div by triggering and image click mechanism

I am currently working with the toggle div function. I am using images to be the triggering point for toggling. For example when a div is close an image with a "plus" signs appears to indicate the user to expand and vice versa for compressing the div. The only issue is that I am using two sets of images for expanding and compressing divs but I can only get a set to work but not both. The is example I have doesn't work well in jsfiddle but if you like to look at it there here is the link: http://jsfiddle.net/sQnd9/4/
Here is my example:
<script type="text/javascript">
function toggle1(showHideDiv, switchImgTag) {
var ele = document.getElementById(showHideDiv);
var imageEle = document.getElementById(switchImgTag);
if(ele.style.display == "block") {
ele.style.display = "none";
imageEle.innerHTML = '<img src="images/Plus_Circle.png"/>';
}
else {
ele.style.display = "block";
imageEle.innerHTML = '<img src="images/Minus_Circle.png"/>';
}
}
</script>
<script type="text/javascript">
function toggle2(showHideDiv2, switchImgTag2) {
var ele = document.getElementById(showHideDiv2);
var imageEle = document.getElementById(switchImgTag2);
if(ele.style.display == "block") {
ele.style.display = "none";
imageEle.innerHTML = '<img src=images/arrow_open.png/>';
}
else {
ele.style.display = "block";
imageEle.innerHTML = '<img src=images/arrow_close.png/>';
}
}
</script>
<div><a id="imageDivLink" href="javascript:toggle1('contentDivImg', 'imageDivLink');"><img src="images/Plus_Circle.png";/></a>Example</div>
<br />
<div id="contentDivImg" style="display:none;">
Example1-Content
</div>
<div><a id="imageDivLink2" href="javascript:toggle2('contentDivImg2', 'imageDivLink2');"><img src="images/Plus_Circle.png";/></a>Example2</div>
<br />
<div id="contentDivImg2" style="display:none;">
Example2-Content
</div>
The problem isn't your code (other than the mistakes that #appclay pointed out). The problem is jsfiddle. Just look at the source code it produces. When you put anything in the "javascript" section it's puts it in it's own namespace, preventing access to those function names outside of that block (so your call to toggle1 for example was throwing an undefined function error).
You can see this in action by defining these functions directly as window. properties. Then your code works as expected. See http://jsfiddle.net/sQnd9/7/
In your own code, you presumably would not encapsulate these function names into their own scope, and it would work as expected (but note again that you should make the changes #appclay pointed out).
Also, you probably shouldn't be doing it this way anyway. You should attach the event handlers in the javascript block.
You're missing the quotes on the img src attribute in the second one
You're also referencing the first function in both examples, so the second function never gets called... Try changing:
<div><a id="imageDivLink2" href="javascript:toggle1('contentDivImg2', 'imageDivLink2');"><img src="images/Plus_Circle.png";/></a>Example2</div>
to
<div><a id="imageDivLink2" href="javascript:toggle2('contentDivImg2', 'imageDivLink2');"><img src="images/arrow_open.png" /></a>Example2</div>
Also, I don't know why you have semicolons in your img tags, they shouldn't be there.

Image slideshow

I am using javascript to slideshow images.Images are loaded only when the user clicks the next button i.e there is no preloading before the slideshow begins. With every image there is a supporting description which is loaded by the same javascript from an array which is stored in the javascript file. The effect of this is such that the description on next image is shown even before the image is displayed. Please suggest me some method so that i can delay displaying the desprition until the image is loaded. Also a loading symbol could be of great help. Please let me know how to do that. Thanks.
You will have to show some code and be more specific if you want more specific answers but in the meanwhile, I think this tutorial could help you out:
JavaScript Timers with setTimeout and setInterval
You need to add an event listener for the image onload event and display your text in that event handler. Unfortunately, as with everything else, not every browser works the same way in this respect. If you google image onload you will find some good suggestions.
Show that image in a dynamically added iframe and add an onload listener to that iframe to show the description only when it loads.
Here's an example:
<script>
var i;
var ifm;
var spinner;
function popupIframeWithImageInit(id, parent, initImageNumber) {
ifm = document.getElementById(id);
i = initImageNumber;
if(ifm === null) {
ifm = document.createElement('iframe');
}
if(!spinner) {
spinner = document.getElementById('spinner');
}
ifm.setAttribute('src', google_logos[i]);
ifm.setAttribute('id', id);
ifm.setAttribute('name', id);
ifm.setAttribute('height', document.body.clientHeight - 50);
ifm.setAttribute('width', '840');//width is fixed because the image is assumed to be fixed size 800
ifm.setAttribute('scrolling', 'yes');
ifm.setAttribute('frameborder', '0');
ifm.style.display= 'none';
ifm.onload = function() {
document.getElementById("description").innerHTML = pic_description[i];
ifm.style.display= '';
spinner.style.display = 'none';
};
document.getElementById(parent).appendChild(ifm);
spinner.style.display = '';
}
function next() {
ifm.src = google_logos[++i];
spinner.style.display = '';
ifm.style.display= 'none';
}
function prev() {
ifm.src = google_logos[--i];
spinner.style.display = '';
ifm.style.display= 'none';
}
function dismissPopupIframeWithImage(parentId, ifmId) {
document.getElementById(parentId).removeChild(document.getElementById(ifmId));
spinner.style.display = 'none';
ifm.style.display= 'none';
return false;
}
//use large images to see the spinner
google_logos = ['http://sharevm.files.wordpress.com/2010/03/googlevsmicrosoft300dpi.jpg',
'http://hermalditaness.files.wordpress.com/2010/01/2.jpg',
'http://tuescape.files.wordpress.com/2008/10/tous20les20logos20google20par20aysoon.jpg',
'http://isopixel.net/wp-content/uploads/2007/02/logos-superbowl.gif'];
pic_description = ['http://sharevm.files.wordpress.com/2010/03/googlevsmicrosoft300dpi.jpg',
'http://hermalditaness.files.wordpress.com/2010/01/2.jpg',
'http://tuescape.files.wordpress.com/2008/10/tous20les20logos20google20par20aysoon.jpg',
'http://isopixel.net/wp-content/uploads/2007/02/logos-superbowl.gif'];
</script>
<img id="spinner" src="http://publish.gawker.com/assets/ged/img/spinner_16.gif" style="position:absolute; left:100px; top:150px; display:none;"/>
<div style="" id="panel"></div>
<div style="" id="description"></div>
<div >
<button onclick="popupIframeWithImageInit('imagePopup', 'panel', 1);">Open</button>
<button onclick="prev();"><-- Prev</button>
<button onclick="next();">Next --></button>
<button onclick="dismissPopupIframeWithImage('panel', 'imagePopup');">Close</button>
</div

Toggle Visibility (Automatically causing one div element to hide when another is rendered visible)

Essentially what I am trying to do is create a website that has all of its content on the home page but only has some of the content visible at any one time. The way I read to do this is through toggling visibility.
The problem I am having is that: Assume the home page, when you first visit the website is blank (the way I want it to be). Lets say you click on the "about us" link. All of a sudden the about us section becomes visible (the way I want it to be). Now the problem that I have come across is when I know lets say click on the "products" link, I want the "products" content to become visible and the "about us" content to become invisible again. (Essentially creating the illusion of opening a new page within the same page).
Here is the code I have come up with so far. I can make certain div elements visible and invisible (onclick) but I can't figure out how to make sure only one div element is visible at any one time.
<script type="text/javascript">
function toggleVisibility() {
document.getElementById("about").style.display = "";
if(document.getElementById("about").style.visibility == "hidden" ) {
document.getElementById("about").style.visibility = "visible";
}
else {
document.getElementById("about").style.visibility = "hidden";
}
}
</script>
<script type="text/javascript">
function toggleVisibility1() {
document.getElementById("products").style.display = "";
if(document.getElementById("products").style.visibility == "hidden" ) {
document.getElementById("products").style.visibility = "visible";
}
else {
document.getElementById("products").style.visibility = "hidden";
}
}
</script>
The links to make the JavaScript work looks like this:
< href="#" onclick="toggleVisibility();">About
< href="##" onclick="toggleVisibility1();"> Products
here is another, simple function
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
if you click here, #foo will change visibility
<div id="foo">blablabla</div>
Without jQuery, you would want to do something like this:
<style type="text/css">
.content {
display: none;
}
#about {
display: block;
}
</style>
<script type="text/javascript">
function toggleVisibility(selectedTab) {
// Get a list of your content divs
var content = document.getElementsByClassName('content');
// Loop through, hiding non-selected divs, and showing selected div
for(var i=0; i<content.length; i++) {
if(content[i].id == selectedTab) {
content[i].style.display = 'block';
} else {
content[i].style.display = 'none';
}
}
}
</script>
About
Products
<div id="about" class="content">About stuff here</div>
<div id="products" class="content">Product stuff here</div>
Example here: http://jsfiddle.net/frDLX/
jQuery makes this much easier, but if you are beginning with JavaScript, sometimes you want to see the programmatic code, so you can tell what is going on.
This is exactly what jquery makes easier. Take this very simple example of what you're trying to achieve:
<style type="text/css">
.section {
display: none;
}
</style>
<script type="text/javascript">
function toggleVisibility(newSection) {
$(".section").not("#" + newSection).hide();
$("#" + newSection).show();
}
</script>
About
Products
<div id="about" class="section">about section</div>
<div id="products" class="section">products section</div>
Simple solution is like this:
<script type="text/javascript">
function toggleVisibility(divid) {
if (divid="about"){
document.getElementById("about").style.visibility = "visible";
document.getElementById("products").style.visibility = "hidden";
}
else if (divid="products")
{
document.getElementById("products").style.visibility = "visible";
document.getElementById("about").style.visibility = "hidden";
}
}
</script>
< href="#" onclick="toggleVisibility('about');">About
< href="##" onclick="toggleVisibility1('products');"> Products
use CSS display: property
element disappear
document.getElementById("products").style.display = "none";
element appear and is displayed as block (default for div)
document.getElementById("products").style.display = "block";
I posted sample code here: jQuery: menus appear/disappear on click - V2
PS
Here you can find nice examples about differences between display and visibility: http://wiw.org/~frb/css-docs/display/display.html

using jquery to insert javascript (for Quicktime) into a <div>

I'm pretty new to javascript and programming and have run into a brick wall with my project. I have a div which contains the javascript to embed a quicktime player, when the page is first loaded no .mov file is pointed at by the page so a placeholder div is 'unhidden' and the player div is set to style.display = 'none'.
So far so good, the user then enters the name of the new movie, the placeholder div is hidden and the player div is unhidden. My problem is that the javascript in the player div didn't run when the div was made visible, if I make the script for the player into a seperate function then call it when the player div is unhidden then the player runs full screen and not in the div.
I've tried using jquery to add the javascript into the div after the div is made visible but can't seem to get $("#player").load(somescript) or $("#player").html(htmlwithjavain) to add the script.
I know the player div contenst can be changed as I can use $("#player").empty(); and $("#player").html(); to manipulate it.
Thanks for reading, hope you can help
Here's the relevant code:-
<html>
<head>
<title>Browse Media Player</title>
<link rel="stylesheet" type="text/css" href="CSS/browser.css" />
<script type="text/javascript">
<!--
var userinterrupt=false;
var runonce=false;
var currentfile;
var basemediapath = "http://10.255.10.71/IsilonBrowse/movfiles/";
var playerheight = 750;
var playerwidth = 900;
var currenttc;
var basetime;
var baseduration;
var currentduration = "no tc available";
var tcoffset = 35990;
var playspeed = 1;
var boolisplaying=true;
var boolonslide=false;
//function to fire off other methods when the DOM is loaded
//Use in place of body onload, using jquery library
//
$(document).ready(function()
{
//showEvents('jquery running');
showhideplayer(null);
});
//-->
</script>
</head>
<body onload="forceslider(); timecode()">
<div class="container">
<div id="timecode_container">
<div class="tc_overlay"></div>
<div id="timecode" class="timecode"></div>
</div>
<div id="player" class="playerdiv" style="display:none;">
**javascript for player goes here...**
</div>
<div id="noclipoverlay" class="playerdiv" style="display:none;">
<p>No media loaded...
</div>
<div id="noclipoverlay2" class="playerdiv" style="display:none;">
<p>loading media....
</div>
</div>
<div id="loadstatus"></div>
<div id="alerts"></div>
</body>
</html>
Now the mainstuff.js file which should add the javascript code:-
//function to switch the player div and mask div is no media file is
//defined in the 'currentfile' variable
//
function showhideplayer(state)
{
if (!currentfile)
{
showEvents('wtf no media');
document.getElementById("player").style.display = 'none';
document.getElementById("noclipoverlay").style.display = 'block';
}
else if (currentfile)
{
document.getElementById("player").style.display = 'block';
document.getElementById("noclipoverlay").style.display = 'none';
showEvents('valid media file');
}
}
//end of showhideplayer
//function to change movie files, note SetResetPropertiesOnReload must be set to false
//otherwise the B'stard player will default all attributes when setURL runs
//
function changemovie(newmovie)
{
oldfile = currentfile;
if (newmovie == currentfile)
{
showEvents('same file requested so no action taken');
return;
}
if (newmovie != currentfile)
{
showEvents('changing movie');
//switch the divs around to hide the 'no media slide'
document.getElementById("player").style.display = 'block';
document.getElementById("noclipoverlay").style.display = 'none';
}
showEvents('movie changed to: '+newmovie);
currentfile=newmovie;
if (!oldfile)
{
$("#player").empty();
showEvents('the old media file was blank');
$("#player").load("/path/loadplayer.js");
}
document.movie1.Stop();
document.movie1.SetResetPropertiesOnReload(false);
document.movie1.SetURL(currentfile);
//showEvents('movie changed to: '+newmovie);
if (boolisplaying)
{
document.movie1.Play();
}
}
[EDIT] and here's the contents of loadplayer.js:-
var movie1 = QT_WriteOBJECT(
currentfile, playerwidth, playerheight, "",
"controller","false",
"obj#id", "movie1",
"emb#id","qt_movie1",
"postdomevents","True",
"emb#NAME","movie1",
"enablejavascript","true",
"autoplay","true",
"scale","aspect",
"pluginspage","http://www.apple.com/quicktime/download/"
);
Without knowing the content of your loadplayer.js file, it will be difficult to give you a solution.
For example, if the script attempts to do a document.write() after the page has loaded, it will create a new page, overwriting the current page. Is that what you mean when you say the quicktime movie is running full screen?
Also it is generally not a good idea to load a SCRIPT element and insert it as HTML. When you add HTML to the page, jQuery finds all the SCRIPT elements and evaluates them in a global context, which might give you unexpected results.
Use QT_GenerateOBJECTText_XHTML or QT_GenerateOBJECTText from AC_QuickTime.js if you'd like to return a string.

Categories