Javascript error [object HTMLParagraphElement] - javascript

I`m begginer in Javascript and I need some help.
So, I need that, when I push the button, paragraph "leftside" appear
<div id="content">
<script>
function myFunction() {
document.getElementById("contentp").innerHTML = leftside;
var x = document.getElementById("leftside")
x.style.display = "normal";
}
</script>
<button id="buttonI" type="button" onclick="myFunction()">Show left side!</button>
<p id="leftside" style="display: none">Left side</p>
<p id="contentp"></p>

x.style.display = "block";
set it block or another value of display except none

You have to append the leftside to the contentp and set its display property to block. normal is not a valid option
<script>
function myFunction() {
document.getElementById("contentp").appendChild(document.getElementById("leftside"));
document.getElementById("leftside").style.display = "block";
}
</script>
<button id="buttonI" type="button" onclick="myFunction()">Show left side!</button>
<p id="leftside" style="display: none">Left side</p>
<p id="contentp"></p>

Related

Hide/Show element on click JS not working properly

I have a simple function when I click on a button to display text for the button, everything is ok but on the first click it's not working then after the second click it's working perfectly can anybody tell me whats my mistake? I have the element hidden in CSS display;none, here is my logic
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#myDIV {
display: none;
}
<button type="button" class="btn btn-primary btn-lg btn-block" onclick="myFunction()">
<div id="myDIV">
This is my DIV element.
</div>
The problem is probably that you didn't close the button tag. So it doesn't find myFunction(). You also need to fetch the computed value of display style not the elements value because css files do not affect the elements styles directly. (e.g. vs style="")
<body>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (getComputedStyle(x).display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<button
type="button"
class="btn btn-primary btn-lg btn-block"
onclick="myFunction()"
>
test
</button>
<div id="myDIV">
This is my DIV element.
</div>
</body>

Javascript - hide/show - multiple buttons - calling 1 function [duplicate]

This question already has answers here:
How can I hide/show a div when a button is clicked?
(9 answers)
Closed 2 years ago.
Please can someone explain this situation?
I want to use the same function (hide/show) for more buttons. How can I call the same function with different buttons?
I found how to do it with one but can't find any solution for 2 or more buttons.
I would like to hide div1 if I click on bt1 and hide div2 if I click on bt2. Thank you for any help...
My current code is:
function myFunction() {
var x = document.getElementById("div1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<html>
<body>
<button id="bt1" onclick="myFunction()">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction()">Button 2</button>
<div id="div2">div2</div>
</body>
</html>
Thank you for your help...
You could pass the ID of the div to your function as a parameter:
function myFunction(el) {
var x = document.getElementById(el);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button id="bt1" onclick="myFunction('div1')">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction('div2')">Button 2</button>
<div id="div2">div2</div>
One way is to pass the ID of the DIV as a function parameter.
function myFunction(id) {
var x = document.getElementById(id);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<html>
<body>
<button id="bt1" onclick="myFunction('div1')">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction('div2')">Button 2</button>
<div id="div2">div2</div>
</body>
</html>
Another way is to pass the button itself, and use DOM navigation, if the DIV to hide and show is always right after the button.
function myFunction(button) {
var x = button.nextElementSibling;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<html>
<body>
<button id="bt1" onclick="myFunction(this)">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction(this)">Button 2</button>
<div id="div2">div2</div>
</body>
</html>
I would do it like so:
Add a data-attribute like data-js-hide="div1"
Add a click event listener for all those elements having the attribute data-js-hide
when clicked use the value "div1" from the attribute data-js-hide
The advantages are that it does not matter where in DOM the elements are. You just need to set the attribute with id, and then on click the item with the id will be hidden or shown accordingly.
function myFunction(event) {
var x = document.getElementById(event.target.dataset.jsHide);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
var buttons = document.querySelectorAll('[data-js-hide]');
buttons.forEach(
button => {
button.addEventListener('click', myFunction);
}
);
<html>
<body>
<button data-js-hide="div1" >Button 1</button>
<div id="div1">div1</div>
<p></p>
<button data-js-hide="div2">Button 2</button>
<div id="div2">div2</div>
<p></p>
<button data-js-hide="div3">Button 3</button>
<div id="div3">div3</div>
</body>
</html>

Toggle between divs: How to show only one div at a time?

I have two div's with different content. I managed to add show-hide div function when clicking on a button. The problem is, when one div is visible and I click on the second button, they are both visible. I would like to show only one div at a time - while one div is shown and I click on another button, the previous div should hide automatically.
I would not want to use jQuery, hope it's possible with pure JavaScript only.
function horTxtFunction() {
var x = document.getElementById("horTxt");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function verTxtFunction() {
var x = document.getElementById("verTxt");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="horTxtFunction()">Horisontaalne tekstiga</button>
<button onclick="verTxtFunction()">Vertikaalne tekstiga</button>
<div id="horTxt" style="display:none;">
<p>Some content here</p>
</div>
<div id="verTxt" style="display:none;">
<p>Some different content here</p>
</div>
Consider wrapping the two <div> tags in a controller <div> tag and then using "state" to control which child <div> will show.
In the example below I am using the attribute dir to hold the state and the CSS to play off the state and the children <div> classes.
var holder = document.querySelector("[dir]");
function horTxtFunction() {
holder.setAttribute('dir', 'hor');
}
function verTxtFunction() {
holder.setAttribute('dir', 'ver');
}
[dir="ver"] > :not(.verTxt),
[dir="hor"] > :not(.horTxt) {
display: none;
}
<button onclick="horTxtFunction()">Horisontaalne tekstiga</button>
<button onclick="verTxtFunction()">Vertikaalne tekstiga</button>
<div dir="hor">
<div class="horTxt">
<p>Some content here</p>
</div>
<div class="verTxt">
<p>Some different content here</p>
</div>
</div>
The major benefit of doing it this way is if you need to add additional children:
var holder = document.querySelector("[dir]");
function toggle(val) {
holder.setAttribute('dir', val);
}
[dir="ver"] > :not(.verTxt),
[dir="hor"] > :not(.horTxt),
[dir="left"] > :not(.leftTxt),
[dir="right"] > :not(.rightTxt) {
display: none;
}
<button onclick="toggle('hor')">Horizontal</button>
<button onclick="toggle('ver')">Vertical</button>
<button onclick="toggle('left')">Left</button>
<button onclick="toggle('right')">Right</button>
<div dir="hor">
<div class="horTxt">
<p>Some content here</p>
</div>
<div class="verTxt">
<p>Some different content here</p>
</div>
<div class="leftTxt">
<p>This is the left text area</p>
</div>
<div class="rightTxt">
<p>This is the right text area</p>
</div>
</div>
Here I change to a single event handler and pass in the section I want to show. Then I had to extend the CSS to handle the new <div> tags. But now growing to more children is just adding the buttons, divs and CSS.
UPDATE
To hide all <div> tags first I made a minor change:
var holder = document.querySelector(".holder");
function toggle(val) {
holder.setAttribute('dir', val);
}
.holder > div {
display: none;
}
[dir=ver] > .verTxt,
[dir=hor] > .horTxt,
[dir=left] > .leftTxt,
[dir=right] > .rightTxt {
display: block;
}
<button onclick="toggle('hor')">Horizontal</button>
<button onclick="toggle('ver')">Vertical</button>
<button onclick="toggle('left')">Left</button>
<button onclick="toggle('right')">Right</button>
<div class="holder">
<div class="horTxt">
<p>Some content here</p>
</div>
<div class="verTxt">
<p>Some different content here</p>
</div>
<div class="leftTxt">
<p>This is the left text area</p>
</div>
<div class="rightTxt">
<p>This is the right text area</p>
</div>
</div>
This hides all of the internal <div> tags and then only shows the correct one based on the value of the dir attribute. Since there is no dir attribute to start then no internal <div>s will show.
You need to make sure to hide the other div and not just show the other.
function horTxtFunction() {
var x = document.getElementById("horTxt");
var otherDiv = document.getElementById("verTxt");
if (x.style.display === "none") {
x.style.display = "block";
overDiv.style.display = "none";
} else {
x.style.display = "none";
overDiv.style.display = "block";
}
}

how to avoid rewriting java script code?

I am looking for a way to avoid rewriting the same code again and again.
I am making a web page that has divs with hide and show option, with the help of a button you toggle between hide and show. I found an easy way to achieve the effect with this code:
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
This works perfectly but gets a bit tedious when you have a dozen or more divs with said effect. Is there a way to avoid having to rewrite the function for each and every div?
Thank you! :)
Easy, parameterize the id:
function myFunction(divId) {
var x = document.getElementById(divId);
and in the HTML pass the id to the function:
<button onclick="myFunction('myDIV')">Try it</button>
<div id="myDIV"> ...</div>
<button onclick="myFunction('myOtherDIV')">Try it</button>
<div id="myOtherDIV"> ...</div>
... and so on ...
You can keep one single function and handle as many divs as you want.
You could run the javascript function with a parameter. So you only have one function and then you only need to change the parameter name. See the example below.
function myFunction(div) {
var x = document.getElementById(div);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction('myDIV')">Try it</button>
<button onclick="myFunction('myDIV2')">Try it2</button>
<div id="myDIV">
This is my DIV element.
</div>
<div id="myDIV2">
This is my DIV2 element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
Just pass the div id to a function
function toggleDiv(divId) {
var x = document.getElementById(divId);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
This works perfectly but gets a bit tedious when you have a dozen or
more divs with said effect
Create an array of such div ids to be toggled and iterate the same, for example
var divIds = ["myDIV1", "myDIV2", "myDIV3"];
divIds.forEach( s => toggleDiv(s) );
Pass a parameter into the function.
function myFunction(divName) {
var x = document.getElementById(divName);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction('myDIV')">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<button onclick="myFunction('myDIV2')">Try it</button>
<div id="myDIV2">
This is my DIV2 element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
using event target and operating relatively on elements, can do the task.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<hr>
<div class="wrapper">
<button onclick="myFunction(event)">Try first</button>
<div class="content">
This is my DIV element.
</div>
</div>
<hr>
<div class="wrapper">
<button onclick="myFunction(event)">Try second</button>
<div class="content">
This is my DIV element.
</div>
</div>
<hr>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction(event) {
var wrapper = event.target.parentElement;
var content = wrapper.querySelector('.content');
if (content.style.display === "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}
}
</script>
</body>
</html>
function myFunction() {
var x = document.getElementsByClassName("myDIV");
for (let i = 0; i < x.length; i++){
x[i].style.display = x[i].style.display == "none" ? "block" : "none";
}
}
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div class="myDIV">
This is my DIV element.
</div>
<div class="myDIV">
This is my DIV element.
</div>
<div class="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
function toggleVisibility(selector) {
const elements = document.querySelectorAll(selector);
elements.forEach( element => {
const isVisible = element.offsetHeight;
if (isVisible) {
element.setAttribute('hidden', '');
} else {
element.removeAttribute('hidden');
}
});
}
<button onclick="toggleVisibility('#myDIV')">Try it</button>
<button onclick="toggleVisibility('.toggle')">Try it with className</button>
<div id="myDIV">
This is my DIV element.
</div>
<div class="toggle">
This is my DIV element.
</div>
<div class="toggle">
This is my DIV element.
</div>

how to add css class with javaScript

I want to be able to print different divs on the same webpage. While I got this functionality working, I want to be able to print my heading, paragraph and div with a class name display_full. I don't want to print div with a class name display_short.
<!DOCTYPE html>
<html lang="en-us">
<head>
<title></title>
<style type="text/css">
.display_full {display:none;}
</style>
</head>
<body>
<div>
<article id="printableArea1">
<header>
<h1>Heading 1</h1>
<p>Some text</p>
<div class="display_short">This is div 1</div>
</header>
<div class="display_full">This is div 2 and I want to print it</div>
<input value="More" onclick="switchVisible(0, this);" type="button">
<input onclick="printDiv('printableArea1')" value="Print" type="button">
</article>
<article id="printableArea2">
<header>
<h1>Heading 2</h1>
<p>Some text</p>
<div class="display_short"><p>This is div 1</p></div>
</header>
<div class="display_full">This is div 2 and I want to print it</div>
<input value="More" onclick="switchVisible(1, this);" type="button">
<input onclick="printDiv('printableArea2')" value="Print" type="button">
</article>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function switchVisible(index, input) {
var div1 = document.getElementsByClassName('display_short')[index];
var div2 = document.getElementsByClassName('display_full')[index];
if (div1) {
if (div1.style.display == 'none') {
div1.style.display = 'block';
div2.style.display = 'none';
} else {
div1.style.display = 'none';
div2.style.display = 'block';
}
}
console.log(input);
if (input.value == "More") input.value = "Less";
else input.value = "More";
}
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
</body>
</html>
Short answer:
Use element.className = "my-class".
Long(er) answer:
Since class is a reserved keyword in JavaScript and earlier versions of JavaScript did not allow accessing a property via the dot operator if the property name is a reserved name (e.g. element.class), the property is called className.
Since you have tagged this jQuery here are some notes in that regard:
Add a class:
$('someselector').addClass('classtoadd');
Toggle a class:(adds or removes this class if it already exists)
$('someselector').toggleClass('classtotoggle');
Select a class:
$('.classtoselect').css('border','solid 1px lime');
Remove selected class(s)
$('someselector').removeClass('classtoremove');//remove one
// remove multiple
$('someselector').removeClass('classtoremove removethisclassalso andthisclassaswell');
$('someselector').removeClass(); // all classes removed
var hasAClass = $('someselector').hasClass('someclass');//returns true if it has the class
Combine the .addClass() with CSS and media and you have it:
CSS:
#media print{ .donotprintme { display: none; } }
code:
$('.display_short').addClass('donotprintme');

Categories