DOM not updating after adding a class to a div? - javascript

I'm trying to write a program that collects all class names in a div, stores them in an array and pushes them all back to the DOM with a class called blue at the end, this is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>some title</title>
<style>
.blue{
width: 200px;
height: 200px;
background: blue;
}
</style>
</head>
<body>
<div class="someClass otherClass" id="box"></div>
<button id="btn">click</button>
</body>
</html>
The thing is, I know how to get all the class names inside the div and even how to push blue (on btn click) inside of that div together with the other values I have collected but why isn't the blue box showing up? What am I missing?
var domManipulation = function(){
var box = document.querySelector('#box');
var btn = document.querySelector('#btn');
var class_list = [];
if(box.classList.length > 0){
for(var i = 0; i < box.classList.length; i++){
class_list.push(box.classList[i]);
}
}
btn.addEventListener('click', function(){
class_list.push("blue");
box.classList.add(class_list);
console.log(class_list);
});
}();
Here is a JsBin and I can't use jQuery btw.

This is the problem:
box.classList.add(class_list);
You can't add a whole array of classes because they end up being comma-separated.
var domManipulation = function() {
var box = document.querySelector('#box');
var btn = document.querySelector('#btn');
var class_list = [];
if (box.classList.length > 0) {
for (var i = 0; i < box.classList.length; i++) {
class_list.push(box.classList[i]);
}
}
btn.addEventListener('click', function() {
class_list.push("blue");
class_list.forEach(function(e){
box.classList.add(e);
})
console.log(class_list);
});
}();
#box {height: 50px; background: #eee}
#box.blue {background: blue}
<div class="someClass otherClass" id="box"></div>
<button id="btn">click</button>

Related

How to trigger an event when a particular HTML element is removed automatically?

Overview of the code: This code consists of an editable div section. Below the div, there is a button which creates a span element, inserts the text "tag" in the span element and finally appends the span element in that editable div
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
<script type="text/javascript">
function addTags()
{
var tag = document.createElement("span");
tag.className = "$(tag)"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
}
$(document).ready(function(){
$('span').keyup(function(){
if(!this.value)
{
alert('this is empty');
}
});
});
</script>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
</body>
</html>
General observation: When I type something inside the div and then click on the button, the HTML DOM will change as:
<div id="sample-div" contenteditable="true">
this is a <span class="$(tag)" contenteditable="false">tag</span>
</div>
Please note that the text "this is a", is provided by me when I type inside the div element. "tag" appears when I click on the input button
Expectation / Trying to achieve: When I delete the text in the span, the DOM will change as:
<div id="sample-div" contenteditable="true">
this is a
</div>
So, my aim is to get the information that the element span is removed when I delete the text in span. I am trying to achieve that by doing the following, which is not correct:
$(document).ready(function(){
$('span').keyup(function(){
if(!this.value)
{
alert('this is empty');
}
});
});
So, my question is how do I get the message "this is empty" when the DOM removes the span element?
You could use a variable as a "tag" counter.
When the amount tags present in the div gets lower than the tag counter, that is when one got deleted.
var tagCount = 0;
function addTags(){
var tag = document.createElement("span");
tag.className = "$(tag)"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
// Increment tagCount
tagCount++;
}
$(document).ready(function(){
$('#sample-div').keyup(function(){
if($(this).find("span").length < tagCount){
alert('One tag was removed');
// Decrement tagCount
tagCount--;
}
});
}); // Ready
#sample-div{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
You probably should use MutationObserver
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
<script type="text/javascript">
'use strict';
function addTags()
{
var tag = document.createElement("span");
tag.className = "$(tag)"
tag.innerHTML = "tag";
tag.contentEditable = false;
document.getElementById('sample-div').appendChild(tag);
}
function onTagRemoved(node)
{
alert(`node ${node.tagName}.${node.className} removed`);
}
//
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
//
// select the target node
let target = document.querySelector('#sample-div');
// create an observer instance
let observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// console.log(mutation);
let node = null;
for (var i = 0; i < mutation.removedNodes.length; i++) {
node = mutation.removedNodes[i];
if (/span/i.test(node.tagName)) {
onTagRemoved(node);
}
}
});
});
// configuration of the observer:
let config = { attributes: false, childList: true, characterData: false }
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop obser
// observer.disconnect();
</script>
</body>
</html>
Tested on Firefox 52

apply jquery filter to an created div?

Hey guys i was wondering if someone could help with some issues on my code.
Basically ive created 4 elements(divs) in an onclick event.From html i've also done so that same button dissapears
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="blackjack2.css">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="blackjack1.js"></script>
</head>
<body>
<button class= "boton" id="start">Play</button>
<button class= "boton" id="hit">Hit</button>
<button class= "boton" id= "stand">Stand</button>
<script type="text/javascript">
var jugar = document.getElementById('start')
var mas = document.getElementById('hit')
var mantener = document.getElementById('stand')
var cuerpo= document.getElementsByTagName('body')[0]
var crear_cartas= function() {
var card= document.createElement('div');
var texto =document.createTextNode("CASINO");
card.setAttribute("class","cartas");
card.appendChild(texto);
cuerpo.appendChild(card);
}
jugar.onclick= function(){
crear_cartas()
crear_cartas()
crear_cartas()
crear_cartas()
jugar.setAttribute('class','ocultar')
}
</script>
</body>
</html>
Up to there is ok , but im not sure if from jquery i can apply a filter that activates on the same onclick event that appears in javascript code (on those 4 created elements )to the even ones so that they make an animation lowering slightly the margin.
I've read about it but i am a bit at sea given that the filter would apply to created elements..
Thank you in advance guys
css class ".cartas" code included:
.cartas{
/*display: none;*/
margin: 260px 75px 0 75px;
display: inline-block;
border-radius: 10px;
border: 1px solid black;
padding-top: 50px;
height:100px;
width:100px;
color: #003366;
font-family: Muli,Helvetica Neue,Helvetica,sans-serif;
text-align: center;
background-color: #f0f8ff;
}
Add an onlcick event to all event divs. This event will add a class that will push the elements below those divs downward using a margin-bottom
Snippet below
var counter = 0;
var jugar = document.getElementById('start')
var mas = document.getElementById('hit')
var mantener = document.getElementById('stand')
var cuerpo = document.getElementsByTagName('body')[0]
var crear_cartas = function() {
card = document.createElement('div');
var texto = document.createTextNode("CASINO");
card.setAttribute("class", "cartas");
card.appendChild(texto);
cuerpo.appendChild(card);
}
jugar.onclick = function() {
for (var x = 0; x < 4; ++x) {
crear_cartas();
if ((x + 1) % 2 == 0) {
card.addEventListener('click', function() {
this.classList.add("move");
})
}
}
jugar.setAttribute('class', 'ocultar')
} //end func
div {
transition: margin-bottom 0.5s;
}
.move {
margin-bottom: 50px;
}
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="blackjack2.css">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="blackjack1.js"></script>
</head>
<body>
<button class="boton" id="start">Play</button>
<button class="boton" id="hit">Hit</button>
<button class="boton" id="stand">Stand</button>
</body>
</html>

How to change 'div' background and text colour using jquery to flash a message And revert back to original colors?

I have a div with id and class names as tab. The css are defined for the div. The original background-color is blue and color is white. I need to flash some text on this div , where the message should flash 3 times with black background and white text and vice versa.
I tried toggleClass. Using this the effect is generated but the previous class css is not restored.
I have tried fade also $("#tab").fadeOut(200).fadeIn(200); , it helps the blinking part but doesnt give the desired results.
Please suggest... Thanks in advance.
This is what i have tried so far:
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<link type="text/css" rel="stylesheet" href="css/styles.css">
<style type="text/css">
.backgroundRed
{
background-color: #cccccc;
color: red;
}
.blink
{
background-color: black;
color: white;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
var flg = 0;
$.fn.blink = function()
{
var i = 0;
for(var i = 0; i <= 3; i++)
{
// attempt#1 //
//blinking works well with this ////
//$("#test").fadeOut(200).fadeIn(200);
// attempt#2 //
//changes looks good but doesnt revert back to original class ////
//$(".backgroundRed").toggleClass("blink");
//$("#test").removeClass("blink");
//$("#test").addClass("backgroundRed");
// attempt #3 //
// doesnt work correctly
if(i >= 3)
{
$("#test").fadeOut(200).fadeIn(200);
$("#test").removeClass("blink");
$("#test").addClass("backgroundRed");
}
else
{
$("#test").fadeOut(200).fadeIn(200);
$("#test").removeClass("backgroundRed");
$("#test").addClass("blink");
}
}
}
$("#tab").click(function(){
$.fn.blink();
});
});
</script>
<html>
<body>
<div id="test" class="backgroundRed" style="height: 200px; width: 400px; ">
<h1>test value</h1>
</div>
<button id="tab">click</button>
</html>
How about something like this:
http://jsfiddle.net/sydzL8Lc/21/
Using https://github.com/madbook/jquery.wait and since you want blink 3 times
$("#test").addClass("blink").wait(400).removeClass("blink").wait(400).addClass("blink").wait(400).removeClass("blink");
Use this blink()
function blink(){
var i = 0;
var obj = setInterval(function(){
if(i == 5)
{
$("#divtoBlink").removeClass("backgroundRed");
clearInterval(obj);
}else{
$("#divtoBlink").toggleClass("backgroundRed");
}
i++;
},100)
}
DEMO

error in javascript toggle class

I have this code for toggling class using pure JavaScript that I found online and it is not working when I am using it in an offline website
my code is -
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
any help would be appreciated
Move the script below the div you are looking for in the source code.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
</body>
</html>
You cannot manipulate the dom before it is ready.
So either load the script that adds the handler at the end of the body tag, or use the DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
Try adding the event handler after the div has rendered - for example in the onload event
Live Demo
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
if (!this.classList) return; // no support
this.classList.toggle('class1');
this.classList.toggle('class2');
}
window.onload=function() {
document.getElementById('div').onclick=classToggle;
}
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
codepen demo
//vanilla js -- toggle active class
// el = object containing the elements to toggle active class and the parent element
var el = {
one: document.getElementById('one'),
two: document.getElementById('two'),
three: document.getElementById('three'),
hold: document.getElementById('hold')
};
// func = object containing the logic
var func = {
toggleActive: function(ele) {
ele = event.target;
var hold = el.hold.children;
var huh = el.hold.children.length;
var hasActive = ele.classList.contains('active');
for (i = 0; i < huh; i++) {
if (hold[i].classList.contains('active')) {
hold[i].classList.remove('active');
}
}
if (!hasActive) {
ele.classList.add('active');
}
}
};
//add listeners when the window loads
window.onload = function() {
var holdLen = el.hold.children.length;
for (i = 0; i < holdLen; i++) {
el.hold.children[i].addEventListener("click", func.toggleActive);
}
};

How to make text using javascript and youtube api clickable

Right now I have a base html page that gets the most popular videos using youtubes api. So far it displays the title of the videos but i'm trying to make those titles clickable. If the title was clicked they would then just be brought to the video on actual youtube. I know that I could theoretically just find the most popular videos then do a clickable link but I want this to more or less auto update everytime a new popular video gets found with the youtube api. Right now I have this basic code.
<html>
<head>
<title>My Videos</title>
<style>
.titlec {
font-size: small;
}
ul.videos li {
float: left;
width: 10em;
margin-bottom: 1em;
}
ul.videos {
margin-bottom: 1em;
padding-left : 0em;
margin-left: 0em;
list-style: none;
}
</style>
<script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script>
<script type="text/javascript">
function showData(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = ['<ul class="videos">'];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t.substr(0, 20);
// var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
html.push('<span class="titlec">', title, '...</span><br /></span></li>');
}
// html.push('</ul><br style="clear: left;"/>');
document.getElementById('videos2').innerHTML = html.join('');
if (entries.length > 0) {
loadVideo(entries[0].media$group.media$content[0].url, false);
}
}
</script>
</head>
<body>
<div id="playerContainer" style="width: 20em; height: 180px; float: left;">
<object id="player">
</object>
</div>
<div id="videos2"></div>
<script
type="text/javascript"
src="http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?time=this_week&alt=json-in-script&callback=showData&max-results=10&format=5">
</script>
</body>
</html>
I am not sure if I exactly understand what you are trying to achieve but I have created a jsfiddle!
Here is the code:
<html>
<head>
<title>My Videos</title>
<script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script>
<script type="text/javascript">
function showData(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = ['<ul class="videos">'];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t.substr(0, 20);
html.push('<li class="titlec">' + title + '</li>');
}
document.getElementById('videos2').innerHTML = html.join('') + '</ul>';
if (entries.length > 0) {
loadVideo(entries[0].media$group.media$content[0].url);
}
}
function loadVideo(e) {
var container = document.getElementById('playerContainer');
var player = document.getElementById('player');
container.removeChild(player);//remove object child
player.setAttribute('data',e);//change link
container.appendChild(player);//add object back
}
</script>
</head>
<body>
<div id="playerContainer" style="width: 20em; height: 180px; float: left;">
<object id="player"></object>
</div>
<div id="videos2"></div>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?time=this_week&alt=json-in-script&callback=showData&max-results=10&format=5">
</script>
</body>

Categories

Resources