how to add css class with javaScript - 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');

Related

In html how to pass div class content (text) to another class or id?

For example, i have <div id="titlebar"></div> inside html, and also i have <div class="name">Content-text</div> inside same html. Now i want pass Content-text of div class name (<div class="name">Content-text</div>) to another my id <div id="titlebar"></div> through css or js. i tried several ways, but no effect
And when i scroll up the html the id titlebar will show the text of class name
My html:
<html>
<body>
<div id="titlebar"></div>
<div class="name">Content-text</div>
</body>
</html>
Css:
#titlebar{
text-align:center;
width: 101%;
position: fixed;
top:0px;
margin-left:-10px;
padding-right:1px;
font-family: Times New Roman;
font-size: 16pt;
font-weight: normal;
color: white;
display:none;
border: none;
}
Javascript:
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 150 || document.documentElement.scrollTop > 150) {
document.getElementById("titlebar").style.display = "block";
} else {
document.getElementById("titlebar").style.display = "none";
}
}
Working Sample, jsFiddle
Please find it here.
<style>
#titlebar{
border: 1px solid black;
}
.name{
border: 1px solid red;
}
</style>
<div>
<div id="titlebar"></div>
<br/>
<div class="name">Content-text</div>
<button id='btn'>
Click to cpoy and put text inside titlebar
</button>
</div>
<script>
document.getElementById('btn').addEventListener('click', function() {
// Find your required code hre
let textInsideDivelementWithclass = document.getElementsByClassName('name')[0].innerText,
titlebarEle = document.getElementById('titlebar');
titlebarEle.innerText = textInsideDivelementWithclass;
});
</script>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var Content_text = $(".name").text();
$("#titlebar").text(Content_text);
});
});
</script>
</head>
<body>
<button>Copy</button>
<div class="name">Content-text</div>
<div id="titlebar">copy here</div>
</body>
</html>
First you get the text of your .name element:
let nameElement = document.querySelector(".name").textContent;
then you get the target element and assign the .name text to it :
document.querySelector("#titlebar").textContent = nameElement;
First of all you should determin an id for your div like this:
<div id="name">Content-text</div>
then use this code:
<script type="text/javascript">
var DivName = document.getElementById('name');
var DivTitlebar = document.getElementById('titlebar');
DivTitlebar.innerHTML = DivName.innerHTML;
</script>
Please try this..
You have to get the content from the div1 and div2 to two seperate variables div1Data and div2Data
Then from the HTML DOM innerHTML Property you can assign the content to your preferred div
function copyContent() {
var div1Data= document.getElementById('div1');
var div2Data= document.getElementById('div2');
div2Data.innerHTML = div1Data.innerHTML;
}
<div id="div1">
Content in div 1
</div>
<div id="div2">
</div>
<button onClick="copyContent()">Click to copy</button>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
<script>
$(document).ready(function(){
var Content_text = $(".name").text();
//alert(Content_text);
$(function() {
$(window).mousewheel(function(turn, scroll) {
if (scroll > 0) $('#titlebar').text('Content_text');
else $('#titlebar').text('Copy here');
return false;
});
});
//$("#titlebar").text(Content_text);
});
</script>
</head>
<body>
<div class="name" style="margin-top:50px;">Content-text</div>
<div id="titlebar" style="margin-top:50px;">Copy here</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 do I use the same link to "re-hide" previously hidden text via Javascript?

The below code snippet shows the invite code when I click "Invite Code". But how do I re-hide the invite code if the same link is clicked again? And can it be done where it cycles back and forth with subsequent clicks? I didn't write this code but merely modified it to my use. I am still very new to this type of thing. Thanks!
<style>
div.hide { display:none; }
div.show { text-align:center; }
</style>
<script type='text/javascript'>
function showText(show, hide) {
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<br>
<font color="red">-</font>Home<font color="red"> / </font><a onclick="showText('text1')" href="javascript:void(0);">Invite Code</a>-</font>
<div id="text1" class="hide"><font color="red">abc123</font></div>
</center></h3>
Simply use this function:
function showText(id)
{
var elem = document.getElementById(id);
if(elem.style.display == 'none')
{
elem.style.display = 'inline';
}
else
{
elem.style.display = 'none';
}
}
<a onClick="showText('text1');" href="#">Show or Hide</a><br/>
<div style="height: 30px;"><div id="text1" style="display: none;">Text to hide or show... WTF?!</div></div>
<div>This text should not move.</div>
PS: This also works for 2 Elements...
Greetings
I really don't see the use for the show class. You could just toggle the hide class on the elements that you want to toggle.
Assume you dont need the show class, then use the classList.toggle function like this
function toggle(target){
document.getElementById(target).classList.toggle('hide');
}
.hide{ display:none }
<button onclick="toggle('test')">Show / Hide</button>
<div id="test" class="hide">Hello world!</div>
save the state with a boolean
var hided = true;
function showText(show,hide){
if (hided){
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
else{
document.getElementById(show).className = "hide";
document.getElementById(hide).className = "show";
}
hided = !hided;
}
fiddle with this code and some of your html : fiddle,
isn't it the expected behavior ?
<html>
<div ID="content" style="display:block;">This is content.</div>
<script type="text/javascript">
function toggleContent() {
// Get the DOM reference
var contentId = document.getElementById("content");
// Toggle
contentId.style.display == "block" ? contentId.style.display = "none" :
contentId.style.display = "block";
}
</script>
<button onclick="toggleContent()">Toggle</button>
</html>
//Code is pretty self explanatory.

javascript hide/unhide, but want an arrow to point down/up on hide/unhide

I have a simple hide/unhide div section using simple JavaScript. I need to have an arrow image, which will toggle the content visibility when clicked, and I want the little arrow to toggle between right/down positions when the content is hidden and unhidden.
HTML content:
<img src="Image_Files/Copyright.png" alt="BioProtege Inc" border="0" />
<img src="Image_Files/Copyright_Arrow_Hidden.png" alt="Arrow" border="0" />
<div id="showorhide">
Copyright 2012+ BioProtege-Inc.Net | LG Fresh Designz
<br />
Contact Us # Lane.Gross#Edu.Sait.Ab.Ca
</div>
JavaScript content:
function showOrHide()
{
var div = document.getElementById("showorhide");
if (div.style.display == "block")
{
div.style.display = "none";
}
else
{
div.style.display = "block";
}
}
You would just use simple Javascript to change the image's src attribute between the two arrows, at the same time you are changing the display attribute:
<script type="text/javascript">
function showOrHide()
{
var div = document.getElementById("showorhide");
if (div.style.display == "block")
{
document.getElementById("img-arrow").src = "Image_Files/arrow-hidden.jpg";
div.style.display = "none";
}
else
{
div.style.display = "block";
document.getElementById("img-arrow").src = "Image_Files/arrow-showing.jpg";
}
}
</script>
<img src="arrow-hidden.jpg" id="img-arrow" alt="" />
<div id="showorhide">
Copyright 2012+ BioProtege-Inc.Net | LG Fresh Designz
<br />
Contact Us # Lane.Gross#Edu.Sait.Ab.Ca
</div>
Even though an answer was already accepted :)
Another way to do it is using Google's jQuery rotation (you need only the "up-arrow" image for this example):
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var value = 0
$("img").click(function(){
$("#showorhide").toggle();
value +=180;
$(this).rotate({ animateTo:value});
});
});
</script>
</head>
<body>
<img src="arrow.jpg" alt="BioProtege Inc" border="0" id="myimg" name="myimg" />
<div id="showorhide">
Copyright 2012+ BioProtege-Inc.Net | LG Fresh Designz
<br />
Contact Us # Lane.Gross#Edu.Sait.Ab.Ca
</div>
</body>
</html>

Categories