Simple Add class with Javascript - javascript

I've this code :
jQuery(document).ready(function($) {
document.getElementById('HAVEATESTHERE').className = "newClass";
}
I want to add a class to #HAVEATESTHERE in javascript, it does not work
Am I missing something ?

You can use classList.add method:
document.getElementById('HAVEATESTHERE').classList.add('first','second', ... );
Also, please make sure you add your class after DOM is rendered.
Take into account, that element.className = 'someClass' will override existing classes with someClass.

elementid is your element`s id and yourclass is that what class do you want add this element.
jQuery(document).ready(function($) {
$('#elementid').addclass('yourClass');
}

Code is fine, see this demo
Ensure that it is either
Added in the window.onload section
window.onload = function(){
document.getElementById('HAVEATESTHERE').className = "class1";
};
if there are already some classes for this element (as suggested by your updated OP), then use classlist to add a new class to that list
document.getElementById('HAVEATESTHERE').classList.add("class1");
- Or the script section is added at the end of body after all the markup is already loaded.

make sure you don't have duplicate IDs for divs. Check this:
function myFunction() {
document.getElementById("myDIV").className = "myclass";
}
.myclass {
width: 200px;
height: 100px;
background-color: blue;
text-align: center;
color: white;
margin-bottom: 10px;
}
<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 100px;
background-color: coral;
text-align: center;
font-size: 25px;
color: white;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to add a class for div.</p>
<div id="myDIV">
Sample div
</div>
<button onclick="myFunction()">Add Class</button>
</body>
</html>

Basically you are trying to mix JavaScript inside jQuery function. Please take care of that. And if you are only using jquery then please use your code
As in this formate
$(document).ready(function(){
$('#HAVEATESTHERE').addclass('newClass');
}
use addclass() function to add class to your div.
with simple js please try to use anonymous function like this
(function(){
var d = document.getElementById("HAVEATESTHERE");
d.className = " newClass";
})();

Related

Set data-attribute in html with jquery or javascript (on click) for a tooltip

I have the following jQuery, CSS and HTML lines:
$("#button").click(function(){
$("#main").data("ot", "test");
});
#main {
display: inline-block;
background-color: red;
padding: 4px;
width: 230px;
text-align: center;
}
#button {
display: inline-block;
padding: 4px;
background-color: green;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main" data-ot="tooltip content" data-ot-delay="0">Div Content (Tooltip Trigger)</div>
<div id="button">Change data-ot to test</div>
OBS: The HTML attribute data-ot is where the tooltip gets the content from...
What I've been trying to do is change the attribute data-ot from it's initial to "test", as shown in the jQuery lines at the snippet.
I even tried using $('#main').attr('data-ot', 'test'); and when I inspect the element in the page it seems to have changed, but the tooltip doesn't recognize the change. During my searches I read that data() and attr() shouldn't be used together for the same porpoise because there might be some conflicts, so I guess that explains why...
I'm really lost on this, any ideas?
As per the plugin documentation you can set or change the attrbutes dynamically.
You can add this code:
var myOpentip = new Opentip($("#main"));
myOpentip.setContent("First Content");
$("#button").click(function() {
myOpentip.setContent("New content");
});
Also, you need to remove data-ot attribute from HTML.
JSFIddle: https://jsfiddle.net/kalimahapps/gu8tu2ev/1/
tooltip value is set when document is built.so if you change it later it will not change the value.

the ID is taking over my class when im using Javascript

I've been sitting with this problem for like 2 hours. What I'm trying to make is a website where you push a button and it changes color. I know this can be done with CSS, but I'm not interested in that.
The main problem is that when I push the button, nothing happens.. However, if I remove the ' #sug from the css' everything works perfectly... So what I want to do, is to make the layout very basic at the beginning, so there's nothing to it, except like the black background, and when I push the buttons it should switch..
Also, I know you can implement onclick in the button tag, but that's not what I'm going for either. I want to know WHY this happens and how I can resolve this problem.
Here's my javascript, CSS and HTML code:
window.onload = setUp;
function setUp() {
document.getElementById("normal").onclick = setNormalStyle;
document.getElementById("crazy").onclick = setCoolStyle;
document.getElementById("insane").onclick = setInsaneStyle;
}
function setNormalStyle() {
var messageBox = document.getElementById("sug");
messageBox.className = "normal";
}
function setCoolStyle() {
var savingTheSecondVar = document.getElementById("sug");
savingTheSecondVar.className = "cool";
}
function setInsaneStyle() {
var savingTheThirdVar = document.getElementById("sug");
savingTheThirdVar.className = "insane";
}
#sug {
background-color: black;
}
.normal {
height: 500px;
background-color: blue;
color: white;
padding: 30px;
margin: auto;
width: 500px;
}
.insane {
height: 500px;
background-color: green;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
.cool {
height: 500px;
background-color: red;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="Struktur.css" />
<script type="text/javascript" src="struktur.js"></script>
<title>My first Javascript project</title>
</head>
<body>
<div id="sug" class="cool insane normal">
<header>
<h1> Welcome to this Javascript site! </h1>
</header>
<section>
<p>
text
</p>
</section>
<button type="button" id="normal">First style</button>
<button type="button" id="crazy">Second style</button>
<button type="button" id="insane">Third style</button>
</div>
</body>
</html>
The problem is your CSS.
#sug{
background-color: black;
}
Overrides the background-color of your classes because it is a more specific selector (i.e. an id selector).
change the rest of your classes in the css to include the id like
#sug.normal, #sug.insane, #sug.cool etc.
Here is a nice article on CSS specificity to help you understand more: https://css-tricks.com/specifics-on-css-specificity/
That's because an id has preference over a class. You will need to specify it like this:
#sug.cool { background: red; }
etc.
You are not removing the background-color provided by the #sug id in CSS onClick() events of the buttons.
Id has more preference over classes
It is a good habit to use below code as classes has spaces between them and it can be used if you want to add more than one class.
messageBox.className += " " + "normal";

How to hide the "body" statement in css and javascript

but after a treatment i want to hide it so i did this:
CSS Code :
body {
text-align: center;
background: url(../images/greenbg.png);
color: #fff;
font-family: myriad pro;
}
body#hide{
visibility: hidden;
}
But i cant't find a way to use the " body#hide" property in my javascript code .
Any idea please?
Thank you in advance
F. Calderan is right, but in this case to avoid any misunderstandings(with already declared IDs) it's better to use css classes.
For Example:
<style>
.inVisible{
visibility: hidden;
}
</style>
<script>
function HideBodyElement(){
document.body.className = "inVisible"
}
</script>
<body>
<button onclick="HideBodyElement()">Hide body</button>
</body>
just use
document.body.id = "hide"
and the css rule you wrote will be applied to your body

document.querySelectorAll length is always 0

I'm trying to create some draggable boxes in javascript. I decided to make an empty class "draggable" in CSS and a "box" class. The code is as follows:
<!DOCTYPE html>
<html>
<head>
<style>
.draggable
{
}
.box
{
position: absolute;
width: 80px; height: 60px;
padding-top: 10px;
text-align: center;
font-size: 40px;
background-color: #222;
color: #CCC;
}
</style>
</head>
<body>
<div class="draggable box">1</div>
<div class="draggable box">2</div>
<div class="draggable box">3</div>
<script>
var draggableStuff = document.querySelectorAll('draggable');
var tabLength = draggableStuff.length;
alert(tabLength);
</script>
</body>
The problem is that tabLength is always zero. I want to get an array filled with all draggable stuff. I'm new to javascript. What have I missed here?
You want to select elements by class, so don't forget about the dot:
var draggableStuff = document.querySelectorAll('.draggable');
Another option is to use document.getElementsByClassName:
var draggableStuff = document.getElementsByClassName('draggable');
I came across this situation. Although it is too old post I would like to help people with my answer:
To select all the elements (no matter what it is, it may be div, span, h1, etc...) with particular attribute
Without value?:
var dragables = document.querySelectorAll('[draggable]');
With value?:
var dragables = document.querySelectorAll('[draggable="true"]');

How to show/hide a div from on mouseover/mouseout on a TR?

Is it possible to attach a popup (div) dynamically to a row in a table such that the popup is rendered by a mouseover, and hidden by a mouseout action?
The code I put together ( see below ) refuses to render the popups, albeit the event handlers are called.
Is what I'm trying to do really possible? From [mouseover() mouseout() jQuery add/removeClass problem, I'm guessing the problem is probably with the CSS
Thought's people?
EDIT:
The class attached to the selected div elements is updated as expected for both, mouseover and mouseout.
<link rel="stylesheet" type="text/css" href='mine.css' />
<html>
<head>
</head>
<body onload="doStuff();">
<table id="myTable">
<tr id="r1">
<td>R1C1</td>
<td>R1C2</td>
<td>R1C3</td>
</tr>
<tr id="r2">
<td>R2C1</td>
<td>R2C2</td>
<td>R2C3</td>
</tr>
<tr id="r3">
<td>R3C1</td>
<td>R3C2</td>
<td>R3C3</td>
</tr>
</table>
</body>
<script type="text/javascript">
function doStuff(){
var lRowCount = document.getElementById("myTable").rows.length;
for(lIter = 0; lIter < lRowCount; lIter += 1){
var lDynamicColumn = document.createElement("td");
var lmyDiv = document.createElement( "div" );
var lId = document.getElementById("myTable").rows[lIter].id;
// div content to be displayed as Text content;
var lText = document.createTextNode( "balderdash!" );
lmyDiv.id= lId + "_popup";
lmyDiv.style.display="none" ;
lmyDiv.appendChild( lText );
/*lDynamicColumn.appendChild(lmyDiv);
document.getElementById("myTable").rows[lIter].appendChild(lDynamicColumn);*/
document.getElementById("myTable").rows[lIter].appendChild(lmyDiv);
document.getElementById("myTable").rows[lIter].onmouseover = function(){
showPopup( lmyDiv.id );
}
document.getElementById("myTable").rows[lIter].onmouseout = function(){
hidePopup( lmyDiv.id );
};
}
alert(document.getElementById("myTable").innerHTML);
}
function showPopup( myId ){
document.getElementById(myId).className="show";
}
function hidePopup( myId ){
document.getElementById(myId).className="hide";
}
</script>
</html>
mine.css
.show{
background-color: #ffffc0;
overflow: auto;
z-index: 100;
border: .1em solid rgb(200, 128, 0);
float: right;
top: -10px;
margin: 5px;
height: inherit;
width: inherit;
position: absolute;
white-space: no-wrap;
}
.hide{
z-index: -1;
}
Add display: block to .show style. Also, your css selectors in the example are wrong, replace show with .show and hide with .hide (if that's not a typo).
On mouse over try document.getElementById('yourcontrolID').style['display']='none';
Hope this works.
I am not sure if this is the problem, but it could be that the lmyDiv is not accessible inside the inline function.
document.getElementById("myTable").rows[lIter].onmouseover = function(){
showPopup( lmyDiv.id );
}
EDIT:
I tested it, and setting the style class dynamically like this did not work in Firefox, IE, Chrome or Safari.
But it did actually work in Opera!
EDIT 2:
I was thinking about something else that could be the issue here:
When the tooltip is shown, is it positioned so that the mouse is inside the tooltip area? In that case, it might be that the onmouseout event on the row is triggered, because the row in question does not longer have "direct contact" with the mouse...
If this is the case, you should add:
lmyDiv.onmouseover = document.getElementById("myTable").rows[lIter].onmouseover;
lmyDiv.onmouseout = document.getElementById("myTable").rows[lIter].onmouseout;
function hide(obj)
{
document.getElementById(obj.id).style.display ='none';
}
onMouseover='hide(this) call this function on div u want to hide.
If you are willing to risk browser incompatibility (and I mean some fairly older browsers we would all like to forget yet always show up when they shouldn't), you should consider simply dropping the javascript all together and simply use pseudo-classes, like so:
.trMessage {
background-color: #ffffc0;
overflow: auto;
z-index: 100;
border: .1em solid #c88000;
float: right;
top: -10px;
margin: 5px;
height: inherit;
width: inherit;
position: absolute;
white-space: no-wrap;
display: none;
}
.trMessage:hover {
display: block;
}
Now you have the option of adding the div to each row in the actual html or keeping the javascript that adds the message box, but without the need for event handlers to adjust for style or class switching. You simply create the boxes the way you already do but use the class "messageBox" for each one. Then the css takes it from there.
Give a try at jQuery!

Categories