Add class to elements which already have a class - javascript

I have a group of divs which I'm dynamically generating when a button is clicked with the class, "brick". This gives them dimension and starting position of top: 0. I'm trying to get them to animate to the bottom of the view using a css transition with a second class assignment which gives them a bottom position: 0;. Can't figure out the syntax for adding a second class to elements with a pre-existing class. On inspection they only show the original class of, "brick".
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="container">
<div id="button" >Click Me</div>
</div>
</body>
</html>
CSS
#container {
width: 100%;
height: 100vh;
padding: 10vmax;
}
#button {
position: fixed;
}
.brick {
position: relative;
top: 0;
height: 10vmax;
width: 20vmax;
background: white;
margin: 0;
padding: 0;
transition: all 1s;
}
.drop {
transition: all 1s;
bottom 0;
}
The offending JS:
var brickCount = function() {
var count = prompt("How many boxes you lookin' for?");
for(var i=0; i < count; i++) {
var newBrick = document.createElement("div");
newBrick.className="brick";
document.querySelector("#container")
.appendChild(newBrick);
}
};
var getBricks = function(){
document.getElementByClass("brick");
};
var changeColor = function(){
getBricks.style.backgroundColor =
'#'+Math.floor(Math.random()*16777215).toString(16);
};
var addDrop = function() {
getBricks.brick = "getBricks.brick" + " drop";
};
var multiple = function() {
brickCount();
getBricks();
changeColor();
addDrop();
};
document.getElementById("button").onclick = function() {multiple();};
Thanks!

You can add a class to an element by doing the following:
element.className = element.className + " drop";
This is just a single string of classnames, so if you're appending, don't forget to add the space.
See https://developer.mozilla.org/en-US/docs/Web/API/Element.className

If you wanna use pure javaScript classList
HTML:
<div id="testdiv" class="brick"></div>
javaScript:
document.getElementById("testdiv").classList.add("anotherclass");
alert(document.getElementById("testdiv").className);
http://jsfiddle.net/Dinizworld/PfWqy/1/
If you wanna use jQuery addClass
HTML:
<div id="testdiv" class="brick"></div>
jQuery:
$(".brick").addClass("numbertwo");
alert($("#testdiv").prop("class"));
http://jsfiddle.net/Dinizworld/UN4gK/

Related

Bi-directional Progression Bar Javascirpt is not working

I want to create a bidirectional bar, one start with negative value the other with positive one. Negative statement in the Javascript code is not working
html code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h3>Example of Progress Bar Using JavaScript</h3>
<input style="height:50px; width:50px; font-size:30px" type = text id="btn1" name = "btn10" > <span id ="option1" style="font-size:30px">Percentage</span>
<p>Pogress Bar</p>
<div style = "position: relative; left: 500px; top: 10px" id="Progress_Status">
<div id="myprogressBar"></div>
</div>
<div style = "position: relative; left: 42.5px; top: -10px" id="Progress_Status2">
<div id="myprogressBar2"></div>
</div>
<br>
<button onclick="Negative_or_Positive()">Start Download</button>
</body>
<script src = "index.js"> </script>
</html>
javascript code
var i = 0;
var My_Button = (document.getElementById("btn1"))
function update() {
var element = document.getElementById("myprogressBar");
var width = parseInt(My_Button.value) || 1;
element.style.width = width + '%';
}
function update2() {
var element = document.getElementById("myprogressBar2");
var width = parseInt(My_Button.value) || 1;
element.style.width = width + '%';
}
function Negative_or_Positive() {
if (My_Button.value > 0){
update()
}else if (My_Button.value <0) {
update2()
}
}
css code
#Progress_Status {
width: 25%;
background-color: #ddd;
}
#myprogressBar {
width: 1%;
height: 20px;
background-color: red;
transition: width .2s;
}
#Progress_Status2 {
width: 25%;
background-color: #ddd;
}
#myprogressBar2 {
width: 1%;
height: 20px;
background-color: blue;
transition: width .2s;
}
the negative statement is not working. When I place a negative value noone of the two bar is growing.
Someone has any idea of why?
You are setting a negative value on the elements width property in your update2() function. Because you know the value of the input element is negative at this point you can simply negate the parsed value:
var width = -parseInt(My_Button.value) || 1;
I put it all in a fiddle and applied the suggested change

trouble hiding scrollbar on div overlay vanilla javascript

I am aware that this question has been asked and answered several times. however, none of the answers given have worked for me 100%
I have a large video gallery that launches a fullscreen overlay to view the video in, and i need the scrollbar to vanish when the video is playing.
I did find one script that works most of the time, but there are two problems with it. First, it does not work in microsoft edge, and second, it is the only script I have left that requires jQuery, and i would dearly love to rid my project of this dependency. here is the script that i have been using. is there a good vanilla javascript alternative? thanks in advance
$(window).load(function() {
$(function() {
$(".noscroll").click(function() {
$(this).next(".hidden").addClass("show");
$(".noscroll").addClass("blurry");
var width = $('body').width();
$("body").css("overflow", "hidden");
var scrollWidth = $('body').width() - width;
$('body').css('margin-right', scrollWidth + 'px')
});
$(".closebtn").click(function() {
$(".hidden").removeClass("show");
$(".noscroll").removeClass("blurry");
$("body").css("overflow", "auto");
$('body').css('margin-right', '0px')
})
});
$(document).mouseup(function(i) {
var container = $(".hidden");
if (!container.is(i.target) && container.has(i.target).length === 0) {
container.removeClass("show");
$(".noscroll").removeClass("blurry")
}
})
});
$('.closeVid').click(function() {
$('body').css('overflow', 'auto')
});
$('.noscroll').click(function() {
$('body').css('overflow', 'hidden')
});
$(document).ready(function() {
$('video').addClass("noscroll")
})
Something like this? https://jsfiddle.net/konrwcaf/1/
<!DOCTYPE html>
<html>
<head>
<title>Simple modal</title>
<style type="text/css">
.modal {
position: absolute;
display: none;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
text-align: center;
z-index: 9000;
}
.modalContent {
background: #fff;
padding: 10px;
min-width: 200px;
min-height: 100px;
display: inline-block;
text-align: left;
position: relative;
top: 50%;
transform: translateY(-50%);
}
body.modalOpen .modal {
display: block;
}
body.modalOpen {
overflow: hidden;
}
</style>
</head>
<body>
<div class="modal">
<div class="modalContent">
<p>I'm the modal</p>
<p><button class="modalCloser">Close modal</button></p>
</div>
</div>
<p><button class="modalOpener">Open the modal</button></p>
<p>Content</p>
<script type="text/javascript">
(function() {
var closeButtons = document.querySelectorAll('.modalCloser');
for (var i = 0, l = closeButtons.length; i < l; i++) {
closeButtons[i].addEventListener('click', function() {
document.body.className = '';
})
}
var openButtons = document.querySelectorAll('.modalOpener');
for (var i = 0, l = openButtons.length; i < l; i++) {
openButtons[i].addEventListener('click', function() {
document.body.className = 'modalOpen';
})
}
})();
</body>
</html>

appendChild removes style

I tried to use appendChild function in order to create a new image node with some style properties. After using it, all properties vanishes. The images supposed to be randomly positioned on the leftSide div, however, actually, they are put align in a row.
<html>
<head>
<title>Matching Game</title>
<style>
#rightSide {
position: absolute;
left: 700px;
border-left: 1px solid black;
width:700px;
height:700px;
}
#leftSide {
width:700px;
height:700px;
position: absolute;
}
</style>
</head>
<body onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id='leftSide'>
</div>
<div id='rightSide'>
</div>
<script>
var numberOfFaces = 5;
var theLeftSide = document.getElementById('leftSide');
var generateFaces = function() {
for(var i = 0; i < numberOfFaces; i++)
{
var img = document.createElement('img');
img.src = 'smile.png';
img.style.top = Math.floor(Math.random()*600);
img.style.left = Math.floor(Math.random()*600);
theLeftSide.appendChild(img);
}
}
</script>
</body>
</html>
http://i.stack.imgur.com/fZaYA.png
Math.floor(Math.random()*600); is going to return a number. Unless the value is 0, the CSS left and top properties require a length. Lengths have units.
Additionally, you haven't changed the position property away from static, so the left and top properties will have no effect as they apply only to positioned elements.
that should solve your problem.
var img = document.createElement('img');
img.style.top = Math.floor(Math.random()*600) + 'px';

Trouble dynamically creating elements with JS

I'm working on a bootcamp and some guys and I have created a group. We are trying to dynamically create html elements using pure JavaScript. The elements are there but we get an error running and we want to be able to go back and use/grab those elements later. Any advice on what we are doing wrong would be much appreciated.
The HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Grid</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="grid"></div>
<script src="js/script.js" type="text/javascript"></script>
</body>
</html>
The js:
(function() {
var grid = document.getElementById("grid");
for (var i = 0; i < 5; i++) {
var temp = document.createElement("DIV");
temp.className = "row";
grid.appendChild(temp);
}
var row = grid.getElementsByClassName("row");
})();
The CSS:
.grid {
height: 100%;
width: 100%;
overflow: auto;
background-color: black;
}
.row {
overflow: auto;
}
.box {
padding: 0;
box-sizing: border-box;
background-color: white;
height: 100px;
float: left;
}
Thanks!
I see no error on your code.
your divs are collected and you can play with them around. take a look to the jsfiddle and open your console. (press F12 or inspect element on right mouse click).
(function() {
var grid = document.getElementById("grid");
for (var i = 0; i < 5; i++) {
var temp = document.createElement("DIV");
temp.className = "row";
grid.appendChild(temp);
}
var row = grid.getElementsByClassName("row");
row[row.length - 1].style.borderColor = "blue";
row[0].style.borderColor = "red";
})();
and the css
.row {
background.color:#f2f2f2;
border: 1px solid #dadada;
margin-bottom:10px;
height:20px;
}
http://jsfiddle.net/hu7a7k0s/

$(".grid").mouseenter doesn't run after I create new divs

My $(".grid").mouseenter doesn't run after I press my new button, which deletes old divs (.grid) and creates new ones. So, what can I change to make it work after that. Also, why are there empty spaces above all .grid divs?
$(document).ready(function(){
createGrid();
$(".grid").mouseenter(function(){
$(this).addClass("hovered")
});
$("#new").click(function(){
clear();
createGrid(prompt("How big would you like your new grid to be (x<64)?"));
});
$("#clear").click(function(){
clear();
});
});
function clear(){
$(".grid").removeClass("hovered");
};
function gridSize(measuring, howBig){
if (howBig==null){
howBig = 16;
}
switch(measuring){
case "height":
return parseInt($("#surface").height()/howBig);
case "width":
return parseInt($("#surface").width()/howBig);
}
};
function createGrid(howBig){
$("#surface").empty();
if(howBig == null || howBig == ""){
for(var i=0; i < 16; i++){
$("#surface").prepend("<div class = 'grid' style = 'width: " +gridSize('width')+"px ; height:"+gridSize('height')+ "px;'></div>");
for(var j=0; j < 15; j++){
$("#surface").prepend("<div class = 'grid' style = 'width: " +gridSize('width')+"px ; height:"+gridSize('height')+ "px;'></div>");
}
}
}
else {
for(var i=0; i < howBig; i++){
$("#surface").prepend("<div class = 'grid' style = 'width: " +gridSize('width', howBig)+"px ; height:"+gridSize('height', howBig)+ "px;'></div>");
for(var j=0; j < howBig-1; j++){
$("#surface").prepend("<div class = 'grid' style = 'width: " +gridSize('width', howBig)+"px ; height:"+gridSize('height', howBig)+ "px;'></div>");
}
}
}
};
* { margin:0; padding:0; }
.wrapper {
width: 800px;
margin: 0px auto;
}
#reset {
width: 60px;
margin : 15px auto;
}
#surface {
margin: 0px auto;
width: 800px;
height: 800px;
}
.grid {
background-color: #D3D3D3;
margin: 0px;
display: inline-block;
}
.hovered {
background-color: black;
}
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "css/styles.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src = "js/script.js"></script>
</head>
<body>
<div class = "wrapper">
<button id ="new">New</button>
<button id ="clear">Clear</button>
<div id = "surface"></div>
</div>
</body>
</html>
Replace:
$(".grid").mouseenter(function(){
$(this).addClass("hovered")
});
with
$("#surface").on('mouseenter','.grid',function(){
$(this).addClass("hovered")
});
This is required because your original code was attaching event handlers to the .grid elements, which you delete and create new elements (which don't have the handlers attached). You could just re-run your original code to attach new handlers when you create new elements, but using event delegation is a much better approach as you only attaching an event handler on one element (#surface) rather than on each individual .grid element, and of course, since you aren't removing and recreating the #surface element, you don't need to detach/re-attach it when you create a new grid.
You can read more about jQuery's on method and event delegation here: http://api.jquery.com/on/
As for the spacing issue, it is because you are using inline-block elements, and inline-elements will preserve atleast one space if present between elements. You can either remove all spaces (and line breaks) between the elements, or you can place font-size:0; on the #surface element to shrink the space size to nothing.
maxSize=16;
$(document).ready(function(){
createGrid(16);
$("#surface").on('mouseenter','div',function(){
$(this).addClass("hovered")
});
$("#new").click(function(){
createGrid(prompt("How big would you like your new grid to be (x<" + maxSize + ")?"));
});
$("#clear").click(function(){
$("#surface>div").removeClass("hovered");
});
});
function gridSize(measuring, howBig){
switch(measuring){
case "height":
return parseInt($("#surface").height()/howBig);
case "width":
return parseInt($("#surface").width()/howBig);
}
};
function createGrid(howBig){
howBig=parseInt(howBig);
if(howBig == NaN || howBig<1 || howBig>maxSize){
howBig=16;
}
$("#surface").empty();
for(var i=0; i < howBig*howBig; i++){
$("#surface").append("<div style='width:" +gridSize('width', howBig)+"px; height:"+gridSize('height', howBig)+ "px;'></div>");
}
};
* { margin:0; padding:0; }
.wrapper {
width: 800px;
margin: 0 auto;
}
#reset {
width: 60px;
margin : 15px auto;
}
#surface {
margin: 0 auto;
width: 800px;
height: 800px;
font-size: 0;
}
#surface>div {
background-color: #D3D3D3;
margin: 0;
display: inline-block;
}
#surface>div.hovered {
background-color: black;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styles.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<div class="wrapper">
<button id="new">New</button>
<button id="clear">Clear</button>
<div id="surface"></div>
</div>
</body>
</html>
I've also taken the liberty to clean up some of the javascript for you.
You will need to use event delegation to work with dynamically created elements
$("#surface").on('mouseenter','.grid',function(){
$(this).addClass("hovered");
});
---> https://learn.jquery.com/events/event-delegation/
it does not work because the divs created after you attach the action to it so you must to use one of this statements :
Example 1:
$("body").on('mouseenter','.grid',function(){
$(this).addClass("hovered");
})
http://api.jquery.com/on/
Example 2:
$("body").live('mouseenter','.grid',function(){
$(this).addClass("hovered");
})
http://api.jquery.com/live/
Example 3:
$("body").delegate('mouseenter','.grid',function(){
$(this).addClass("hovered");
})
http://api.jquery.com/delegate/

Categories