Changing display property dynamically - javascript

I want to change the style:display property (none or block) of my div (displaydiv) according to the value of a global variable (disp). I want to check the value of this variable on page load and set the styel: display according to the value disp.
i set the value of disp as "none" in javascript.
i want to change the value within HTML TAG
But this div is always visible.
Please help me

<script>
function hidemydiv() {
if(disp == 'none') document.getElementById('displaydiv').style.display = 'none';
}
</script>
<body onload="hidemydiv()">
<div id="displaydiv">
Lorem ipsum dolor sith amet
</div>
</body>
I just wonder what kind of global variable disp is. Is it in javascript? PHP? Where/when/how do you set it?

We can't tell without code but it sounds very much like you're executing your change-style JS inline before the target DIV has loaded.
Does your browser report errors on the page?
Is your JS code bound to the onload event somehow?
Is the style actually applied but overidden (check with firebug)?

Attach a function to the window onload event.
window.onload = function () {
var elem = document.getElementById(divId);
if (disp === "none") {
elem.style.display = "none";
}
else {
elem.style.display = "block";
}
};

Related

Display content that was initially hidden onload

resultTable is initially hidden. When play button is clicked, the game will run and it will display the finalscore inside the hidden content. I need a function to display the finalscore. Currently the showResult function I have is not working (obviously)
I deleted unnecessary contents because the whole thing is a little big and messy. Hope the code still makes sense.
<body onload="loadGame()">
<div>
<button onclick="playButton()" id="play">Play</button>
</div>
<div id="resultTable" >
<span id="result"></p>
</div>
<script>
function loadGame(){
var hideResult = document.getElementById("resultTable");
hideResult.style.display = "none";
}
function playButton(){
playGame();
showResult();
}
function playGame(){
/*Some code here*/
document.getElementbyId("result").innerHTML = "finalscore";
}
function showResult(){
var show = document.getElementById("resultTable"); //fixed.
show.style.display = "block";
}
</script>
</body>
Change the way you are finding the element to set its display as block or none. You are using the "getElementsByClassName" method, but there is no element with such classname in the DOM.
Moreover, the "getElementsByClassName" will return you an array of all the elements, if found, in the DOM and you have to loop through the array to access it.
function showResult(){
document.getElementById("resultTable").style.display = "block";
}

How to toggle <p> once you click on <button> for second time?

function testFunction(){
var x = document.getElementById("test");
x.style.fontSize = "40px";
x.style.color = "blue";
}
<p id= "test"> **I would like to hide this once user clicks on button for a second time!!** </p>
<button type= "button" onclick="testFunction()"> Click Here! </button>
I am wondering how I hide the paragraph once a user clicks on the button a second time? When user clicks on button the first time, javascript is enabled and the code is shown, but then paragraph stays on the screen even after user clicks for a second time on button. Is there some way I can hide what is displayed if user clicks on button for a second time?
<p id= "test"> **I would like to hide this once user clicks on button for a second time!!** </p>
<script>
function testFunction(){
var x = document.getElementById("test");
x.style.fontSize = "40px";
x.style.color = "blue";
}
</script>
<button type= "button" onclick="testFunction()"> Click Here! </button>
First of all, I don't think that you should alter the style of elements trough js, that is what css is for (exceptions exist obviously). You could however alter the state of an element, and have your css react to that. I find it keeps your code a lot easier to maintain, and you know automatically where to look for what when you need to change something.
Have a look at the fiddle I prepared: http://jsfiddle.net/7xy39ufz/1/
So I added a state to your markup (I went for a data attribute, but a class or something could do as well)
<p id="test" data-visible="0">...</p>
<button type="button" id="button">...</button>
Then in the css I added a few lines that would react to the state:
p {
font-size: 50px;
color: blue;
}
p[data-visible="0"] {
display: none;
}
p[data-visible="1"] {
display: block;
}
And with all that done the javascript becomes very simple
document
.getElementById('button')
.addEventListener('click', testFunction, false);
function testFunction(){
var x = document.getElementById("test");
x.dataset.visible = x.dataset.visible == 0 ? 1 : 0;
}
Note that I moved the binding of the click event to js as well, in part because I couldn't get it to work in the fiddle (a scope / sandbox issue i guess), but mainly because I find js belongs with js, not in your markup.
Update
The real 'magic' is indeed being done in this line:
x.dataset.visible = x.dataset.visible == 0 ? 1 : 0;
This is basically a short hand for
if (x.dataset.visible == 0) {
x.dataset.visible = 1;
} else {
x.dataset.visible = 0;
}
(look up 'ternary' if you want to learn more about the syntax)
This code switches the data-visible attribute of you p between 1 and 0. The css reacts to that by setting the display property of that paragraph (that is what the attribute selector [data-visible="..."] is for).
I hope this clarifies things for you. Feel free to ask if you want me to explain further.
<script>
function testFunction(){
if (x.style.fontSize == "40px"){ //you could use another condition, or a global var here
document.getElementById("test").style.display="none";
}
else{
var x = document.getElementById("test");
x.style.fontSize = "40px";
x.style.color = "blue";
}
}
</script>

Using script variables in html body

I want to call the variable from the script to body.
Here is my script code. I want to take the rightanswers and wronganswers values to use in html body.
GetFeedback = function (a) {
if (a == CorrectAnswer) {
rightanswers++;
} else {
wronganswers++;
}
lock = true;
}
You need to use the Document Object Modle. You have different methods with JavaScript to create and insert elements into the DOM. As for example:
var element = document.createElement('p');
var body = document.body;
body.appendChild(element);
With that code you are creating an element, then appendig it into the body. And that is pure JavaScript. You could use Mootools or jQuery, and It is goign to be simpler. But JavaScript doesn't work like PHP for example, where you can use the variables mixed up with the HTML.
And if you want to trigger the function from the HTML you need to bind thtat function to an event. For example clicking on a link would be.
HTML
Click Here
JS
var b = document.getElementById('button');
b.click = function(){
GetFeedback();
}
Make sure you're declaring the variable (we can't see that in the code provided) by using var:
<script>
var GetFeedback = function (a) {
if (a == CorrectAnswer) {
rightanswers++;
} else {
wronganswers++;
}
lock = true;
</script>
Then in your HTML, you can use feedback like this (although, it's not good practice to use the below, it's merely for demonstration purposes):
Hello
you can use jquery to change the html on the page.
GetFeedback = function(a){
if(a==CorrectAnswer){
rightanswers++;
}else{
wronganswers++;
}
lock=true;
$('p:first').html('Right Answers: '+rightanswers+' <br> Wrong Answers: '+wronganswers);
};
and have this as your html
<body>
<p></p>
Get Feedback
</body>

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.

Collapsing JavaScript/HTML div on page load?

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>

Categories