How to add to html article class variable from js - javascript

I have 6 styles in css and i want to use this code to apply them randomly:
<script>
function getRandom(max) {
return "style" + Math.floor(Math.random() * max);
}
document.getElementById('XXX').innerHTML = getRandom(6);
</script>
And I need to add XXX to article class
<article class="XXX">
This code doesn't work :(

First set a ID to the article tag
<article class="XXX" id="someId">
Then to set class to article use below code
var element = document.getElementById("someId");
element.className=getRandom(6);

Hope this helps!
//randomize plugin
(function($) {
$.rand = function(arg) {
if ($.isArray(arg)) {
return arg[$.rand(arg.length)];
} else if (typeof arg === "number") {
return Math.floor(Math.random() * arg);
} else {
return 4; // chosen by fair dice roll
}
};
})(jQuery);
//your list of classes
var items = ["class-1", "class-2", "class-3", "class-4", "class-5"];
//executes on page load
$("#addRandom").removeClass().addClass(jQuery.rand(items));
//button to inject random class
$("#randomize").click(function() {
var item = jQuery.rand(items);
$("#addRandom").removeClass().addClass(item);
});
#addRandom {
display:block;
width: 100px;
height: 100px;
margin: 10px
}
.class-1 {
background-color: purple;
}
.class-2 {
background-color: blue;
}
.class-3 {
background-color: green;
}
.class-4 {
background-color: yellow;
}
.class-5 {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="addRandom" class="">
</div>
<button id="randomize">randomize</button>

If you just need to add a CSS class to your element, the answer is plain easy:
document.getElementById("your-element").classList.add("your-class");
For more information, see classList.

Thanks to all! Here is a code that works as needed:
<script>
const elements = document.querySelectorAll('article');
elements.forEach(element => {
function getRandom(max) {
return "style" + Math.floor(Math.random() * max);
}
element.classList.add(getRandom(6));
});</script>

Related

Is there a way to add class to all elements

I browsed thru various similar questions, but I found nowhere real help on my problem. There are some Jquery examples, but none of them weren't applicable, since I want to do it by vanilla JavaScript only.
The Problem
I have rating widget which I want to build like every time I click on "p" element, eventListener adds class "good" on all p elements before and on the clicked one, and remove class good on all that are coming after the clicked one.
My Thoughts
I tried to select all the "p" elements and iterate over them by using a for loop to add class before and on clicked element, and to leave it unchanged or remove after, but somewhere I am doing it wrong, and it adds class only on clicked element not on all previous ones.
My Code
function rating () {
var paragraph = document.getElementsByTagName('p');
for (var i = 0; i < paragraph.length; i++) {
paragraph[i].addEventListener('click', function(e) {
e.target.className='good';
})
}
}
rating();
Result
Expected result is that every p element before the clicked one, including clicked one should be having class good after click and all the ones that are after the clicked one, should have no classes.
Actual Result: Only clicked element is having class good.
Using Array#forEach , Element#nextElementSibling and Element#previousElementSibling
General logic behind this is to loop through all the previous and next sibling elements. For each element, add or remove the class .good until there are no more siblings to handle.
const ps = document.querySelectorAll('p');
ps.forEach(p => {
p.addEventListener("click", function() {
let next = this.nextElementSibling;
let prev = this;
while(prev !== null){
prev.classList.add("good");
prev = prev.previousElementSibling;
}
while(next !== null){
next.classList.remove("good");
next = next.nextElementSibling;
}
})
})
p.good {
background-color: red;
}
p.good::after {
content: ".good"
}
p {
background-color: lightgrey;
}
<div id='rating'>
<p>*</p>
<p>*</p>
<p>*</p>
<p>*</p>
<p>*</p>
</div>
Alternative:
Using Array#slice to get the previous and next group of p's.
const ps = document.querySelectorAll('p');
ps.forEach((p,i,list) => {
p.addEventListener("click", function() {
const arr = [...list];
const previous = arr.slice(0,i+1);
const next = arr.slice(i+1);
previous.forEach(pre=>{
pre.classList.add("good");
})
next.forEach(nex=>{
nex.classList.remove("good");
});
})
})
p.good {
background-color: red;
}
p.good::after {
content: ".good"
}
p {
background-color: lightgrey;
}
<div id='rating'>
<p>*</p>
<p>*</p>
<p>*</p>
<p>*</p>
<p>*</p>
</div>
function setup() {
var paragraph = document.querySelectorAll("p");
for (p of paragraph) {
p.onclick = (event) => {
let index = Array.from(paragraph).indexOf(event.target);
[].forEach.call(paragraph, function(el) {
el.classList.remove("good");
});
for (let i = 0; i <= index; i++) {
paragraph[i].classList.add("good");
}
}
}
}
//Example case
document.body.innerHTML = `
<div id='rating'>
<p>*</p>
<p>*</p>
<p>*</p>
<p>*</p>
<p>*</p>
</div>`;
setup();
The key ingredient is to use Node.compareDocumentPosition() to find out if an element precedes or follows another element:
var paragraphs;
function handleParagraphClick(e) {
this.classList.add('good');
paragraphs.forEach((paragraph) => {
if (paragraph === this) {
return;
}
const bitmask = this.compareDocumentPosition(paragraph);
if (bitmask & Node.DOCUMENT_POSITION_FOLLOWING) {
paragraph.classList.remove('good');
}
if (bitmask & Node.DOCUMENT_POSITION_PRECEDING) {
paragraph.classList.add('good');
}
});
}
function setup() {
paragraphs = [...document.getElementsByTagName('p')];
paragraphs.forEach((paragraph) => {
paragraph.addEventListener('click', handleParagraphClick);
});
}
setup();
#rating { display: flex; }
p { font-size: 32px; cursor: default; }
p:hover { background-color: #f0f0f0; }
.good { color: orange; }
<div id='rating'>
<p>*</p>
<p>*</p>
<p>*</p>
<p>*</p>
<p>*</p>
</div>`

How do I supplant jQuery's toggleClass method with pure JavaScript?

How can I turn this piece of jQuery code into JavaScript?
$('#element').click(function(){
$(this).toggleClass('class1 class2')
});
I have already tried the following pieces of code, but to no avail.
First one is:
var element = document.getElementById('element'),
classNum = 0; // Supposing I know that the first time there will be that class
element.onmousedown = function() {
if (classNum === 0) {
this.classList.remove("class1");
this.classList.add("class2");
classNum = 1;
}
else if (classNum === 1) {
this.classList.remove("class2");
this.classList.add("class1");
classNum = 0;
}
}
Second one is:
var element = document.getElementById('element'),
classNum = 0; // Supposing I know that the first time there will be that class
element.onmousedown = function() {
if (classNum === 0) {
this.className -= "class1";
this.classList += "class2";
classNum = 1;
}
else if (classNum === 1) {
this.classList -= "class2";
this.classList += "class1";
classNum = 0;
}
}
Any answer that doesn't suggest that I stick with jQuery will be greatly appreciated.
[EDIT]
I've tried all of your solutions, but haven't been able to get it right. I believe it's because I didn't state clearly that the element has multiple classes like so:
class="class1 class3 class4"
And what I want is basically to replace class1 with class2 and toggle between them.
Update:
In response to comments, classList.toggle is a pure javascript solution. It has nothing to do with jQuery as one comment implies. If there is a requirement to support old versions of IE then there is a shim (pollyfill) at the MDN link below. And this shim, if needed, is far superior to the accepted answer.
Using classList.toggle certainly seems like the simplest solution. Also see Can I Use classList for browser support.
element.onclick = function() {
'class1 class2'.split(' ').forEach(function(s) {
element.classList.toggle(s);
});
}
Run the snippet to try
box.onclick = function() {
'class1 class2'.split(' ').forEach(function(s) {
box.classList.toggle(s);
stdout.innerHTML = box.className;
});
}
/* alternative
box.onclick = function() {
['class1', 'class2'].forEach(function(s) {
box.classList.toggle(s);
stdout.innerHTML = box.className;
});
}
*/
.class1 { background-color: red;}
.class2 { background-color: blue;}
.class3 { width: 100px; height: 100px; border: 1px black solid;}
click me:
<div id="box" class="class1 class3"></div>
<div id="stdout"></div>
classNum is a local variable.
Every time the event handler is called, you get a new variable, which has nothing to do with the value from the last call.
You want that to be a global variable.
Or, better yet, check classList.contains instead.
From: You might not need jQuery
$(el).toggleClass(className);
Is replaced by:
if (el.classList) {
el.classList.toggle(className);
} else {
var classes = el.className.split(' ');
var existingIndex = classes.indexOf(className);
if (existingIndex >= 0)
classes.splice(existingIndex, 1);
else
classes.push(className);
el.className = classes.join(' ');
}
Then simply wrap that function call within a document.getElementById('elementId').click
See fiddle: https://jsfiddle.net/2ch8ztdk/
var s = document.getElementById('element');
s.onclick=function(){
if(s.className == "class1"){
s.className = "class2"
} else {
s.className = "class1"
}
}
Your code is close, but your classNum variable isn't iterative. Try this:
var element = document.getElementById("element");
var numCount = 0;
element.addEventListener('click', function() {
if (numCount === 0) {
this.className = "";
this.className += " class1";
numCount++;
} else {
this.className = "";
this.className += " class2";
numCount = 0;
}
});
.class1 {
color: red;
}
.class2 {
color: blue;
}
<div id="element">click me</div>
you can use classList, but it only support IE 10+
Demo
var eles = document.querySelectorAll('#element');
var classNames = 'one two';
for(var i = 0; i < eles.length; i ++){
eles[i].onclick = function(e){
toggleClass.call(this, classNames);
}
}
function toggleClass(names){
var sp = names.split(' ');
for(var i = 0; i < sp.length; i++){
this.classList.toggle(sp[i]);
}
}
UPDATED MY ANSWER TO SUPPORT MULTIPLE CLASSES PER ELEMENT
https://jsfiddle.net/pwyncL8r/2/ This will now allow the element to already have n classes and still swap only one, retaining the other classes.
HTML
<div id="div1" style="width: 100px; height: 100px;" class="backBlack left100"</div>
<input type="button" id="swapButton" value="Css Swap" />
CSS
.backBlack {
background-color: black;
}
.backRed {
background-color: red;
}
.left100 {
margin-left: 100px;
}
JS
swapButton.onclick = function() {
var curClassIsBlack = (' ' + document.getElementById("div1").className + ' ').indexOf(' backBlack ') > -1
if (curClassIsBlack) {
document.getElementById("div1").className =
document.getElementById("div1").className.replace(/(?:^|\s)backBlack(?!\S)/g, '')
document.getElementById("div1").className += " backRed";
} else {
document.getElementById("div1").className =
document.getElementById("div1").className.replace(/(?:^|\s)backRed(?!\S)/g,'')
document.getElementById("div1").className += " backBlack";
}
}

Selecting Multiple Elements height();

I am just wondering why this jQuery won't work:
hdr = $('.header-wrapper, #top-bar, #new-showroom-header').height();
So as you can see I am trying to get the height of multiple elements and store them all within my variable. I'd expect jQuery to add all of the elements heights together to create a final value however when I console.log the variable hdr I get the height of the first element selected.
Any idea how I can select all and store them into my var?
Use $.each() to get total sum of height.
var hdr = 0;
$('.header-wrapper, #top-bar, #new-showroom-header').each(function () {
hdr += $(this).height();
});
FIDDLE DEMO
You can write a jQuery plugin for this scenario. :)
The following code below will return an array of heights based on the provided selectors.
[20,30,80]
jQuery Plugin
(function($) {
$.fn.heights = function() {
return this.map(function() {
return $(this).height();
}).toArray();
};
}(jQuery));
var heights = $('.header-wrapper, #top-bar, #new-showroom-header').heights();
document.body.innerHTML = JSON.stringify(heights); // [20,30,80]
body { font-family: monospace; white-space: pre; }
.header-wrapper { height: 20px; }
#top-bar { height: 30px; }
#new-showroom-header { height: 80px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="page-wrapper">
<div class="header-wrapper"></div>
<div id="top-bar"></div>
<div id="new-showroom-header"></div>
</div>
Alternatively, you could build a cache of heights along with their selectors.
{
"html>body>div>.header-wrapper": 20,
"html>body>div>#top-bar": 30,
"html>body>div>#new-showroom-header": 80
}
(function($) {
$.reduce = function(arr, fn, initVal) {
if (Array.prototype.reduce) { return Array.prototype.reduce.call(arr, fn, initVal); }
$.each(arr, function(i, val) { initVal = fn.call(null, initVal, val, i, arr); });
return initVal;
};
$.fn.heights = function() {
return $.reduce(this, function(map, el) {
map[$(el).fullSelector()] = $(el).height();
return map;
}, {});
};
$.fn.fullSelector = function() {
var sel = $(this)
.parents()
.map(function() { return this.tagName.toLowerCase(); })
.get()
.reverse()
.concat([this.nodeName])
.join(">");
var id = $(this).attr('id'); if (id) { sel += '#' + id; };
var cls = $(this).attr('class'); if (cls) { sel += '.' + $.trim(cls).replace(/\s/gi, '.'); };
return sel;
}
}(jQuery));
var heights = $('.header-wrapper, #top-bar, #new-showroom-header').heights();
document.body.innerHTML = JSON.stringify(heights, null, 2);
body { font-family: monospace; white-space: pre; }
.header-wrapper { height: 20px; }
#top-bar { height: 30px; }
#new-showroom-header { height: 80px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="page-wrapper">
<div class="header-wrapper"></div>
<div id="top-bar"></div>
<div id="new-showroom-header"></div>
</div>
Credit for the selector algorithm goes to Jesse Gavin.
No you can not get all element height using .height(); function
first you apply $.each() loop in collection then you can get height one by one
following code help you
$.each($('.header-wrapper, #top-bar, #new-showroom-header'),function(ind,item){
var Height = $(item).height();
});

Change div background after certain amounts of clicks

I have a script that shows the amount of clicks on a button and I want to change the background image of another div after a certain amount of clicks, in this case 5. At the moment the click amount works fine but the other part wont react to it. The second code works if I manually type 5 as the starting value for #click.
This is what I have so far:
$('#button').click(function () {
$('#clicks').html(function (i, val) {
return val * 1 + 1
});
});
if ($('#clicks').html() == 5) {
$("#first").addClass('red');
}
<div id="clicks">0</div>
<div id="first">first</div>
<div id="button">click</div>
#first {
width: 100px;
height:100px;
}
.red {
background:red;
}
You need to check the value after each click modification. also you should compare the returned value with string:
$('#button').click(function () {
$('#clicks').html(function (i, val) {
return val * 1 + 1
});
//check for new value
if ($('#clicks').html() == "5") {
$("#first").addClass('red');
}
});
Try this:
$(function() {
var count = 0;
$('div').click(function() {
if (count++ == 5) {
$(this).addClass('red');
}
})
});
.red {
background-color: red;
}
div {
width: 100px;
height: 100px;
background-color: blue;
}
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<div></div>
Increase the value and check if it's 5 within the click function.
$('#button').click(function () {
$('#clicks').html(function (i, val) {
val++;
if (val == 5)
$("#first").addClass('red');
return val;
});
});
You can also change it every 5 clicks by using the modulus and toggleclass.
$('#button').click(function () {
$('#clicks').html(function (i, val) {
val++;
if (val % 5 == 0)
$("#first").toggleClass('red');
return val;
});
});

Random number into div and then let delete divs in sequence. How?

So, i want to make game for my child. Have low experience in JS.
Scenario:
Have for example 4 square divs with blank bg. After refresh (or win) i want to:
Generate random numbers into div (1...4). And show them in them.
Then let player delete those divs by clicking on them, but in sequence how divs are numbered.
*For example after refresh divs have those numbers 2 3 1 4. So, user has to have rights to delete first div numbered 1 (2 3 _ 4) and so on.* If he clicks on 2 it get error , div stays in place, and user can try again delete right one.
It game for learning numbers. I have the begining.
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
</head>
<body>
<div class="grid">
<div id="Uleft"></div>
<div id="Uright"></div>
<div id="Dleft"></div>
<div id="Dright"></div>
</div>
<script>
$(".grid").children( "div" ).on("click", function(){
$(this).css("visibility", "hidden");
});
</script>
</body>
</html>
css.css
.grid {
margin: 0 auto;
width: 430px;
}
#Uleft, #Uright, #Dleft, #Dright {
border: 1px solid black;
width: 200px;
height: 200px;
margin: 5px;
}
#Uright {
float: right;
background-color: red;
}
#Uleft {
float: left;
background-color: blue;
}
#Dleft {
float: left;
background-color: green;
}
#Dright {
float: right;
background-color: yellow;
}
So, i guess i have use jQuery as well, but i dont know how to make it dynamic and different after refresh of page. Please help :)
http://jsfiddle.net/bNa8Z/
There are a few things you have to do. First you have to create a random array which you use sort and Math.random() to do then, you need insert the text in the squares. Find the min of the visible squares and then remove/alert depending if its the min value.
// sort by random
var rnd = [1,2,3,4].sort(function() {
return .5 - Math.random();
});
// map over each div in the grid
$('.grid div').each(function(ii, div) {
$(div).text(rnd[ii]); // set the text to the ii'th rnd
});
function minVisible() {
var min = 1e10; // a big number
$('.grid div').each(function(ii, div) {
// if not visible ignore
if ($(div).css('visibility') === "hidden" ){
return;
}
// if new min, store
var curFloatValue = parseFloat($(div).text());
console.log(curFloatValue);
if (curFloatValue < min) {
min = curFloatValue;
}
});
return min;
}
$(".grid").children( "div" ).on("click", function(){
var clickedFloatValue = parseFloat($(this).text());
if (clickedFloatValue == minVisible()) {
$(this).css("visibility", "hidden");
} else {
alert("sorry little tike");
}
});
Updated jsfiddle http://jsfiddle.net/bNa8Z/2/
Roughly this is what it would look like:
var selected = {};
$('.grid div').each(function(idx){
var is_done = false;
do{
var rand = Math.floor((Math.random()*4)+1);
if( selected[rand] == undefined ){
$(this).html(rand);
selected[rand] = 1;
is_done = true;
}
}while(!is_done);
});
alert("Start the game");
var clicked = [];
$('.grid').on('click', 'div.block', function(){
var num = $(this).html();
if( num == clicked.length + 1 ){
//alert(num + " is correct!");
clicked.push(num);
$(this).addClass("hide");
}else{
alert("Failed!");
}
if( clicked.length == 4 ){
alert("You Won!");
}
});
HTML:
<div class="grid">
<div class="block" id="Uleft"></div>
<div class="block" id="Uright"></div>
<div class="block" id="Dleft"></div>
<div class="block" id="Dright"></div>
</div>
Added CSS:
#Uleft, #Uright, #Dleft, #Dright {
position:absolute;
...
}
#Uright {
left:220px;
top:0px;
background-color: red;
}
#Uleft {
left:0px;
top:0px;
background-color: blue;
}
#Dleft {
left:0px;
top:220px;
background-color: green;
}
#Dright {
left:220px;
top:220px;
background-color: yellow;
}
.hide {
display: none;
}
See the working version at
JSFiddle
You will need to re-"run" the fiddle per game.
please try it. I think that It will help you.
var generated_random_number_sequesce = function(){
var number_array = [];
var number_string = '';
var is_true = true;
while(is_true){
var ran_num = Math.round(1 + Math.random()*3);
if(number_string.indexOf(ran_num) == -1 && ran_num < 5){
number_array[number_array.length] = ran_num;
number_string = number_string + ran_num;
if(number_array.length == 4){is_true = false;}
}
}
return number_array;
}
var set_number_on_divs = function(){
var number_array = generated_random_number_sequesce();
$(".grid").children().each(function(index, element){
$(this).attr('data-div_number' , number_array[index]);
});
}
set_number_on_divs()
var clicked = 0;
$(".grid").children( "div" ).on("click", function(){
clicked += 1;
var current_div_number = $(this).attr('data-div_number');
if( parseInt(current_div_number) == clicked){
$(this).css("visibility", "hidden");
} else{
clicked -= 1;
alert('error');
}
});

Categories