Show div onclick not working (Javascript) - 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>

Related

how can I alter my code to hide element on load?

I'm using this js code to show/hide elements on my site:
<script>
function myFunction3() {
var x = document.getElementById("dsec-three");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Can anyone help me to set it so the elements are hidden on load and only show once activated?
you can use class for show/hide elements same as :
function showHide(){
element = document.getElementById('element1');
showHideEle(element)
}
function showHideMulti(){
elements = document.getElementsByClassName('multi');
Array.from(elements).forEach(ele => {
showHideEle(ele)
});
}
function showHideEle(ele){
let isHide = ele.classList.contains('hide');
if (isHide) {
ele.classList.remove("hide");
} else {
ele.classList.add("hide");
}
}
.hide {
display: none
}
<p class="hide" id="element1">para 1</p>
<button onclick="showHide()">Show/Hide</button>
<br />
<p class="hide multi">para 2</p>
<p class="hide multi">para 3</p>
<p class="hide multi">para 4</p>
<button onclick="showHideMulti()">Show/Hide Multi</button>
Your function myFunction3 already does the job of hiding and showing the relevant elements. All you need to do now is invoke the function when your document loads. You can do this by adding the following line inside your <script>:
document.addEventListener("load", myFunction3);
If you need the elements to stay hidden by default and show them after the document loads, you'll need to set the display property of those elements to none either via inline CSS.
Example (if your element is a div) :
<div id="dsec-three" style="display:none">
...
</div>
what do you mean by activated?
if you mean that after the load of your page, you would need an event listener.
follow these steps:
set the initial display of your element to none.
create an event listener like load: and add your function there:
document.addEventListerer('load', function(){
myFunction3();
})
the above code is telling the browser: 'when ever the page loads, call this function'

make paragraph element appear and disappear when heading is clicked [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I'm attempting to make a p tag appear and disappear when I click on the h1 I feel I have a good understanding of the process in JavaScript (obviously I don't but I cant seem to get it to do anything at all (I'm really new to this, like only a couple weeks into JS)
here is the Code
<script type="text/javascript">
function hideAway() {
var pText = document.getElementsByClassName('imgpar');
if (pText.style.display === 'none') {
pText.style.display = 'block';
}else if (pText.style.display === 'block') {
pText.style.display = 'none';
}
}
</script>
<div class="left-image">
<h1 onClick= hideAway()>header</h1>
<img title="skater name" src="skater.jpeg" alt="skater">
<p class= 'imgpar'>skateboard bio
</p>
</div>
Few problems:
.getElementByClassName() is not a function. It should be getElementsByClassName()
.getElementsByClassName() returns an array - in your case you should be selecting the first element
Your if statements are redundant. They can be shortened to a simple if-else statement
You'll need to explicitly apply display:block in the style attribute on the p element so pText.style.display returns something. If you don't explicity set it, you will have to click twice to hide the p element.
This should work:
<div class="left-image">
<h1 onClick= hideAway()>header</h1>
<img title="skater name" src="skater.jpeg" alt="skater">
<p class= 'imgpar' style="display:block">skateboard bio
</p>
</div>
<script type="text/javascript">
function hideAway() {
var pText = document.getElementsByClassName('imgpar')[0];
if (pText.style.display == 'block') {
pText.style.display = 'none';
}else{
pText.style.display = 'block';
}
}
</script>
Easy solutions
HTML:
<div class="left-image">
<h1>header</h1>
<img title="skater name" src="skater.jpeg" alt="skater">
<p class= 'imgpar'>skateboard bio</p>
</div>
JS:
$(document).ready(function(){
$("h1").click(function(){
if ($("p").hasClass("showEle")) {
$('p').removeClass('showEle')
} else {
$('p').addClass('showEle');
}
});
});
CSS:
.showEle {
display: none;
}

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

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>

JS: Hiding DIV based on another DIVs content

I am looking to hide a number of DIVs based upon the specific text of another DIV. My Javascript (below) isn't working.
The HTML:
<div id="LEGEND">abAB</div>
<div id="small-a"></div>
<div id="small-b"></div>
<div id="big-a"></div>
<div id="big-b"></div>
If the LEGEND DIV contains the text a, then I want it to show only DIV small-a.
If the LEGEND DIV contains the text bA, then I want it to show only DIV small-b and big-a.
The Javascript:
<script>
window.onload = function ShowHide{
if (document.getElementById('LEGEND').indexOf("a") > 0){
document.getElementById('small-a').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("b") > 0){
document.getElementById('small-b').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("A") > 0){
document.getElementById('big-a').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("a") > 0){
document.getElementById('big-b').style.display = 'block';}
</script>
You are forgetting a couple of things.
A function declaration should be like this
function functionName(args) {
}
You have to hide the divs using style.display = "none"
Example:
<div id="LEGEND">abB</div>
<div id="small-a" style="display: none;">This is small-a</div>
<div id="small-b" style="display: none;">This is small-b</div>
<div id="big-a" style="display: none;">This is big-a</div>
<div id="big-b" style="display: none;">This is big-b</div>
<script>
function showElement(id) {
document.getElementById(id).style.display = "block";
}
window.onload = function ShowHide() {
var legend = document.getElementById("LEGEND").innerHTML;
if(legend.indexOf("a") != -1) showElement("small-a");
if(legend.indexOf("b") != -1) showElement("small-b");
if(legend.indexOf("A") != -1) showElement("big-a");
if(legend.indexOf("B") != -1) showElement("big-b");
}
</script>
The problem is that your code changes the other div elements to block-level elements when div is already a block-level element. You need to set them not to display initially using CSS and then reveal them in the JavaScript.
Try this instead:
<div id="LEGEND">abAB</div>
<div id="small-a" style="display: none;"></div>
<div id="small-b" style="display: none;"></div>
<div id="big-a" style="display: none;"></div>
<div id="big-b" style="display: none;"></div>
<script type="text/javascript">
window.onload = function() {
if (document.getElementById('LEGEND').indexOf('a') > 0) {
document.getElementById('small-a').style.display = 'block';
...
// etc.
}
}
</script>
First, try making sure the window.onload is being called:
window.addEventListener('load', ShowHide, false);
function ShowHide()
{...
Second, you should be looking at the InnerHTML of the element:
if (document.getElementById('LEGEND').innerHTML.match("a") == "a"){...
Third, each if statement should also contain an else (replace divName with real div names):
else {
document.getElementById('divName').style.display = 'none'}
Hope that helps!
~md5sum~
EDIT:
Also, I'm not 100% sure on this, but I believe that the syntax:
window.onload = function ShowHide{
will completely fail. I think that the syntax should be:
window.onload = function(){
If me, I will do like this. you dont need to touch HTML part, everything is done in javascript.
you can extend it to CDEFGH...
and you don't need to set <div id="small-X" style="display: none;"> for each tags too. :-)
<body>
<script>
window.onload=function(){
x=document.getElementsByTagName("div");
//first hide everything with small- or big-
for(i in x)
if(/small-|big-/.test(x[i].id))
x[i].style.display="none";
//then turn on each tags based on LEGEND
x= document.getElementById("LEGEND").innerHTML;
for(i=0;i<x.length;i++)
document.getElementById((x[i]<='Z'?'big-':'small-')+x[i].toLowerCase()).style.display='block';
}
</script>
<div id="LEGEND">aAB</div>
<div id="small-a">a</div>
<div id="small-b">b</div>
<div id="big-a">A</div>
<div id="big-b">B</div>
</body>
You need to set the style.display property to none.

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