How do I use the CSS display property on clicking a button? - javascript

I am new to JavaScript, and I've been trying to use a button to show a particular element. I need to be able to clear some content of the page and display new content on the click of a button. I cant change pages, and need to stay on the same page. I am trying to change the display property of the element I want to display.
This is what I have tried:
//CSS//
<style>
p {
display: visible;
}
div {
display: none;
}
</style>
//HTML//
<body>
<p id="textElem">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
<button onclick="displayDiv()">View Form</button>
<div id="hiddenElem">
<form></form>
</div>
<body>
//JS//
<script>
const textElement = document.getElementById('textElem');
cont hiddenElement = document.getElementById('hiddenElem');
function displayDiv() {
}
</script>
I do not know what the syntax is to reference CSS properties in Java Script. What I want to do is to change the display property of the paragraph to hidden and the display property of the div to visible when the button is clicked.
Could someone please help me out with this?

Meet the style object.
function displayDiv() {
textElement.style.display = 'none';
hiddenElement.style.display = 'block';
}

You can simply use the javascript style property for this. Check the below code for your requirement:
function displayDiv() {
document.getElementById('firstElem').style.display = 'none';
document.getElementById('secondElem').style.display = 'block';
}
.hide {display:none;}
<div id="firstElem">First Page</div>
<div id="secondElem" class="hide">Second Page</div>
<button onclick="displayDiv()">Click Here</button>

Style rule display: visible - does not exist. And you can style these in these ways.
1 - Use property display:
function displayDiv() {
hiddenElement.style.display = 'block';
textElement.style.display = 'none';
}
2 - Use property setProperty():
function displayDiv() {
hiddenElement.style.setProperty('display', 'block');
textElement.style.setProperty('display', 'none');
}
3 - Use property cssText:
function displayDiv() {
hiddenElement.style.cssText = 'display: block;'
textElement.style.cssText = 'display: none;'
}
This property (cssText) will allow you to set the list of styles you need. Like that:
hiddenElement.style.cssText = 'display: none; color: green; background-color: white';

You can directly use it in an index.html file.
<html>
<head>
<style>
.hidden{display:none;}
</style>
</head>
<body>
<p id="paragraph">HTML, CSS, and JS are awesome.</p>
<button onclick="displayDiv()">View Form</button>
<div id="divBox" class="hidden">
<form>
<label>Name:</label><input/>
</form>
</div>
<script>
const paragraph = document.getElementById('paragraph');
const divBox = document.getElementById('divBox');
function displayDiv() {
paragraph.classList.add('hidden');
divBox.classList.remove('hidden');
}
</script>
<body>
</html>

Related

Show div onclick not working (Javascript)

Javascript newbie here. Anyone could let me know what is wrong with my code? The div-to-show does not show after click and I can't figure out why...
let div = document.getElementById('div-to-show');
function openDiv() {
if (div.style.display === 'none') {
div.style.display = 'block';
}
}
#div-to-show {
display: none;
}
<p onclick="openDiv">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
There are 2 problems here.
First, you aren't invoking the function with onclick="openDiv" - you have to put () after a function name to invoke it, eg onclick="openDiv()".
Secondly, although you have a CSS rule of display: none, that doesn't result in the CSS property on the element itself changing; it remains the empty string:
let div = document.getElementById('div-to-show');
function openDiv() {
console.log(div.style.display);
}
#div-to-show {
display: none;
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
Instead, to check whether the element is being displayed, you can check whether its offsetParent is null:
let div = document.getElementById('div-to-show');
function openDiv() {
div.style.display = div.offsetParent === null ? 'block' : 'none';
}
#div-to-show {
display: none;
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
For the general case of checking what CSS rules are being applied to a particular element, you can use getComputedStyle:
let div = document.getElementById('div-to-show');
const styleProp = div.style;
const styleDec = window.getComputedStyle(div);
function openDiv() {
styleProp.display = styleDec.display === 'none' ? 'block' : 'none';
}
#div-to-show {
display: none;
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
<!DOCTYPE html>
<html>
<head>
<style>
#div-to-show{
display: none;
}
</style>
</head>
<body>
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
<script type="text/javascript">
let div = document.getElementById('div-to-show');
function openDiv(){
if(window.getComputedStyle(div).display === 'none'){
div.style.display = 'block';
}
}
</script>
</body>
</html>
In your code is wrong the way you write onclick in this tag <p>, you need to write onclick in this way:
<p onclick="openDiv()">Clique</p>
and try again.
You should mention function name correctly on onclick. onclick=openDiv should be replaced to onclick=openDiv().
You should define the display css style directly on the tag to get div.style.display on javascript. document.getElementById('...').style will only contain the style attributes which are defined on html tag style attribute only so to compare, it will be needed to set display attribute on html file directly.
let div = document.getElementById('div-to-show');
function openDiv() {
if (div.style.display === 'none') {
div.style.display = 'block';
}
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show" style="display: none;">
<p>I am visible</p>
</div>
Hi as some other examples here explains, you should use the addEvenlListener. If you only what to show the div on the click event you do not need a if statement. You can add a class to the div that sets the display:none. Then in the code you only need to call the remove on the classList on the div. This will not throw an error or do anything if the class is not in the classList. So no need to implement any check logic.
Using the hidden class makes so you do not need to know what the display value was on the div element initially. Less to worry about.
https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/remove
let div = document.getElementById('div-to-show')
document.getElementById('p-button').addEventListener("click", openDiv);
function openDiv() {
div.classList.remove('hidden');
}
#div-to-show.hidden {
display: none;
}
<p id="p-button">Clique</p>
<div id="div-to-show" class="hidden">
<p>I am visible</p>
</div>

Hide and show text by click on div

I have a question concerning an event onclick. I found this code during my research. My question is : even before the click the text already appears, is it possible to hide the text until we click on the actual button. And is it possible to have numerous onclick event working seperately that is o say only open the text above it? Thank you
<html>
<head>
<title>Show and hide div with JavaScript</title>
<script>
function showhide()
{
var div = document.getElementById("newpost");
if (div.style.display !== "block") {
div.style.display = "block";
}
else {
div.style.display = "none";
}
}
</script>
</head>
<body>
<div id="newpost">
<p>This div will be show and hide on button click</p>
</div>
<button id="button" onclick="showhide()">Click Me</button>
</body>
</html>
happy coding :)
function showhide() {
var div = document.getElementById("newpost");
div.classList.toggle('hidden');
}
.hidden{
display : none;
}
<html>
<head>
<title>Show and hide div with JavaScript</title>
</head>
<body>
<!--if you want by default hidden then add class .hidden in new post -->
<div id="newpost" class="hidden">
<p>This div will be show and hide on button click</p>
</div>
<button id="button" onclick="showhide()">Click Me</button>
</body>
</html>
make it by default as none in style on display property.
<div id="newpost" style="display:none">
<p>This div will be show and hide on button click</p>
</div>
Yes. In your stylesheet, have the #newpost div display: none and also add a modifier class, .visible with display: block. Lastly in your function you could toggle the .visible class via classList.toggle and you should be good to go:
var div = document.getElementById('newpost');
document.getElementById('button').addEventListener('click', showhide);
function showhide() {
div.classList.toggle('visible');
}
#newpost {
display: none;
}
#newpost.visible {
display: block;
}
<button id="button">Click Me</button>
<div id="newpost">
<p>This div will be show and hide on button click</p>
</div>
In JQuery you can add multiple on click events to a button like so:
$("#button").on("click", function(){
$("#newpost").toggle();
});
$("#button").on("click", function(){
$("#secondpost").toggleClass("bold");
});
#newpost{
display:none;
}
.bold{
font-weight:bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head>
<title>Show and hide div with JavaScript</title>
</head>
<body>
<div id="newpost">
<p>This div will be show and hide on button click</p>
</div>
<button id="button">Click Me</button>
<p id="secondpost">toggle bold</p>
</body>
</html>
The first on click toggles the paragraph above.
The second on click toggles a class on the last paragraph that makes it bold.
html
<body>
<div class="growth-step js--growth-step">
<div class="step-title">
<div class="num">2.</div>
<h3>How Can Aria Help Your Business</h3>
</div>
<div class="step-details ">
<p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
management organization with expertise. </p>
</div>
</div>
<div class="growth-step js--growth-step">
<div class="step-title">
<div class="num">3.</div>
<h3>How Can Aria Help Your Business</h3>
</div>
<div class="step-details">
<p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
management organization with expertise. </p>
</div>
</div>
</body>
js
$(document).ready(function(){
$(".js--growth-step").click(function(event){
$(this).children(".step-details").slideToggle(500);
return false;
});
$(".js--growth-step .step-details").click(function(event) {
event.stopPropagation();
});
});

Hide div after showing it with javascript

I'm using javascript to show a hidden div by clicking a button. After the div is displayed, I want to be able to click the button again and hide the div, and so on...
Here is my javascript:
<script type="text/javascript">
function showDiv() {
document.getElementById('dropdownText').style.display = "block";
}
</script>
This is the button:
<input type="button" name="answer" value="+" onclick="showDiv()" />
This is the hidden div:
<div id="dropdownText" style="display:none;">
This is the dropdown text.
</div>
You can e.g. bind specified class to the element and just toggle it.
function showDiv() {
document.getElementById('dropdownText').classList.toggle("hidden");
}
.hidden {
display: none;
}
<input type="button" name="answer" value="+" onclick="showDiv()" />
This is the hidden div:
<div id="dropdownText" class='hidden'>
This is the dropdown text.
</div>
If you tagged this question with jQuery as well, so I guess you could use the .toggle function, like this -
$('#answer').click(function() {
$('#dropdownText').toggle();
}
If you want to stick up with javascript only, your showDiv() function should look like this -
function showDiv() {
let text = document.getElementById('dropdownText');
if (text.style.display === 'none') {
text.style.display = 'block';
}
else {
text.style.display = 'none';
}
}
You should capture the current style every time a button is clicked, since you want to 'toggle' it back to the opposite state.
You simply need to do this:
const drop = document.getElementById('dropdownText')
const toggleDropdown = _ => {
const cl = drop.classList
cl.contains('hide')?cl.remove('hide'):cl.add('hide')
}
#dropdownText.hide {display:none}
/* DropDown Styles for this demo */
#dropdownText {width: 10em; height: 4em; background: green}
<button onclick='toggleDropdown()'>Toggle Div</button>
<div id='dropdownText'></div>
Note: Click Run Code Snippet to see the code in action.
The way it works is by detecting if it has the hide class and based on that, toggle that class.
The actual hiding and showing is done via CSS!
<div id="dropdownText" style="display:none">
This is the dropdown text.
</div>
<script type="text/javascript">
function showDiv() {
var x = document.getElementById('dropdownText');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>

How to show a hidden div by javascript?

I want to hide a div if javascript is turned off and show that div if javascript enabled but I don't want to use <noscript> as in chrome and opera it has some issues. So what I am doing is something like this:
<div id="box" style="display:none"></div>
<script type="text/javascript">
document.getElementById("box").style.visibility = "visible";
</script>
But the javascript part does not show the div. How can I make it visible is javascript is enabled. Also tried $('#box').show(); but that too didn't work.
Use style.display
document.getElementById("box").style.display = "block";
You need to set the attribute display to block
document.getElementById("box").style.display = "block";
You are trying to toggle between visibility, which is similar, but a different property.
You are using display: none, not visibility: hidden.
Solution add visibility: hidden instead of display none if you want to use that instead of display. They work a little different.
You can set:
<div id='box' style='display: none;'>...</div>
And in your script code:
document.getElementById('box').style.display = 'block';
change display to visibility
<div id="box" style="visibility:none"></div>
<script type="text/javascript">
document.getElementById("box").style.visibility = "visible";
</script>
or change js
<div id="box" style="display:none"></div>
<script type="text/javascript">
document.getElementById("box").style.display = "block";
</script>
You could also use a mix of CSS and Javascript to accomplish this:
HTML/Javascript
<script type="text/javascript">
document.documentElement.className += 'js-ready';
</script>
CSS
div#box { display: none; }
.js-ready div#box { display: block !important; }

How to use JavaScript to change div backgroundColor

The HTML below:
<div id="category">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</div>
When mouseover the content of div then it's backgroundColor and the h2 (inside this div) backgroundColor change (just like the CSS: hover)
I know this can use CSS (: hover) to do this in modern browser but IE6 doesn't work.
How to use JavaScript (not jQuery or other JS framework) to do this?
Edit:how to change the h2 backgroundColor too
var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
this.style.backgroundColor = 'green';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
this.style.backgroundColor = 'transparent';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'transparent';
};
Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.
Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.
Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.
So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.
One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.
In conclusion, here is the code which I would use for such tasks:
//for adding a css class
function onOver(node){
node.className = node.className + ' Hover';
}
//for removing a css class
function onOut(node){
node.className = node.className.replace('Hover','');
}
function connect(node,event,fnc){
if(node.addEventListener){
node.addEventListener(event.substring(2,event.length),function(){
fnc(node);
},false);
}else if(node.attachEvent){
node.attachEvent(event,function(){
fnc(node);
});
}
}
// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
if(div.className.match('content')){
connect(div,'onmouseover',onOver);
connect(div,'onmouseout',onOut);
}
}
And you CSS whould be like this:
.content {
background-color: blue;
}
.content.Hover{
background-color: red;
}
.content.Hover h2{
background-color : yellow;
}
Access the element you want to change via the DOM, for example with document.getElementById() or via this in your event handler, and change the style in that element:
document.getElementById("MyHeader").style.backgroundColor='red';
EDIT
You can use getElementsByTagName too, (untested) example:
function colorElementAndH2(elem, colorElem, colorH2) {
// change element background color
elem.style.backgroundColor = colorElem;
// color first contained h2
var h2s = elem.getElementsByTagName("h2");
if (h2s.length > 0)
{
hs2[0].style.backgroundColor = colorH2;
}
}
// add event handlers when complete document has been loaded
window.onload = function() {
// add to _all_ divs (not sure if this is what you want though)
var elems = document.getElementsByTagName("div");
for(i = 0; i < elems.length; ++i)
{
elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
}
}
<script type="text/javascript">
function enter(elem){
elem.style.backgroundColor = '#FF0000';
}
function leave(elem){
elem.style.backgroundColor = '#FFFFFF';
}
</script>
<div onmouseover="enter(this)" onmouseout="leave(this)">
Some Text
</div>
It's very simple just use a function on javaScript and call it onclick
<script type="text/javascript">
function change()
{
document.getElementById("catestory").style.backgroundColor="#666666";
}
</script>
Change Bacckground Color
This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover attribute just like with a elements.
Example:
div.classname:hover
{
background-color: black;
}
This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox
Happy programming!
If you are willing to insert non-semantic nodes into your document, you can do this in a CSS-only IE-compatible manner by wrapping your divs in fake A tags.
<style type="text/css">
.content {
background: #ccc;
}
.fakeLink { /* This is to make the link not look like one */
cursor: default;
text-decoration: none;
color: #000;
}
a.fakeLink:hover .content {
background: #000;
color: #fff;
}
</style>
<div id="catestory">
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
</div>
To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.
For example:
var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
if (child.nodeType == 1 && child.className == "content") {
child.onmouseover = function() {
this.style.backgroundColor = "#FF0000";
}
child.onmouseout = function() {
// Set to transparent to let the original background show through.
this.style.backgroundColor = "transparent";
}
}
}
If your h2 has not set its own background, the div background will show through and color it too.
You can try this script. :)
<html>
<head>
<title>Div BG color</title>
<script type="text/javascript">
function Off(idecko)
{
document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
}
function cOn(idecko)
{
document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
}
function hOn(idecko)
{
document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->
}
</script>
</head>
<body>
<div id="catestory">
<div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
<h2 id="h21">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
<h2 id="h22">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
<h2 id="h23">some title here</h2>
<p>some content here</p>
</div>
</div>
</body>
<html>

Categories