Change style for array of DIVS - javascript

I have 100 DIVS in an array called 'lights', appended to the page with a unique ID. Some of those DIVS are also in another array called 'frozen'.
How can I change the background color of the DIVS in 'lights' but not the divs in the 'frozen' array?
For example, to change all of the divs I would use:
for(var l=0;l<LIGHTS_NUMOF;l++){
$("#light"+l).css("background-color", "#ff0000");
}
Generating the array:
var LIGHTS_NUMOF = 100;
var lights = [];
for(var l=0;l<LIGHTS_NUMOF;l++){
var newLight = $("<div class=\"light\" id=\"light"+l+"\"></div>");
$(".lights").append(newLight);
lights.push(newLight);
}
However, this obviously changes ALL of the divs.
How do I avoid changing the DIVS which are in the 'frozen' array?
Ideally I would like to express lights.backgroundcolor = 'red' where DIV isn't 'frozen'.
Adding DIV to 'frozen':
$( ".light" ).click(function() {
frozen.push(this);
});

If you are actually looking at items in the DOM, you can easily do what you want using jQuery.not() like the following example.
$(document).ready(function() {
$("#changeLights").on("click", function() {
$(".lights").not(".frozen").addClass("frozen");
});
});
div {
height : 50px;
width : 50px;
background-color : #CCC;
margin: 5px;
float: left;
}
.frozen {
background-color : #F00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="lights"></div>
<div class="lights"></div>
<div class="lights frozen"></div>
<div class="lights"></div>
<div class="lights frozen"></div>
<div class="lights frozen"></div>
<input id="changeLights" type="button" value="Change" />

Try this:
for(var l=0;l<LIGHTS_NUMOF;l++){
if(frozenArray.indexOf(lightsArray[l]) == -1){ // if id is not in frozen array
$("#light"+l).css("background-color", "#ff0000");
}
}

First of all...
Try modify this part of your code
$(".light").click(function() {
$(this).addClass("frozen");
});
Then to get all of that is not frozen, do this:
$(".light").not(".frozen").css("background-color", "#ff0000");

Related

How to set jquery unbind as toggle

Following is my script to show and hide content on click of a div.
I also want to disable other div elements until the first div is clicked again.
$('.leader-pic-wrapper').click(function(){
var $el = $(this);
var bottom = $el.position().top + ($el.outerHeight(true) - 30);
$('.leader-pic-overlay').toggle();
$('.leader-pic-wrapper').not(this).toggleClass('inactive-leader');
/*$(".inactive-leader").unbind("click");*/
$(".inactive-leader").off("click");
$(this).next('.leader-profile-wrapper').css('top', bottom);
$(this).next('.leader-profile-wrapper').toggle();
});
I don't understand how to toggle the unbind statement. I tried toggling a class called inactive-leader and apply unbind to that class, but its not working.
Basically I want to set unbind on
leader-pic-wrapper
Thanks
My option is approach this with a different view. Without bind and unbind the event just exclude the items with the first selector using :not(), and as you are doing add a class to the elements you want to exclude; please check this snippet:
$('body').on('click', '.box:not(".disabled")', function() {
if ($('.disabled').length) {
$(this).siblings().removeClass('disabled')
$(this).animate({
'width': '80px'
}, 300)
} else {
$(this).siblings().addClass('disabled')
$(this).animate({
'width': '160px'
}, 300)
}
})
.box {
display: inline-block;
height: 80px;
width: 80px;
background: tomato;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
This logic on your code will look like this:
//Delegate the event since we are add/remove the class
//Target the elements that aren't inactive
$('body').on('click', '.leader-pic-wrapper:not(".inactive-leader")', function() {
var $el = $(this);
var bottom = $el.position().top + ($el.outerHeight(true) - 30);
//Check if exists some inactive elements to handle 1/2 click
if ($('.inactive-leader').length) {
//Target other leader-pic-wrapper elements, use sibling or the method you need based on your markup
$(this).siblings().removeClass('inactive-leader')
//...ACTIONS - This will act as the second click
} else {
$(this).siblings().addClass('inactive-leader')
//...ACTIONS - This will act as the first click
}
});

How to hide dynamically created html element with a dynamic ID

I have a dynamically created html elements under a for loop in JavaScript, these dynamic elements also has a dynamic id, my question is how can I hide the dynamically created elelment with a dynamic id. Thank you.
This is my code so far. I want to target the dynamic id and hide it.
product_list += '<div class="plProductContainer hide" data-pids="' + a_data.products[i].pid + '" id="'+a_data.products[i].pid+'">';
It has a dynamic id.
I would recommend you will use classes instead of id, but for this example you could use something like this. hide the element using a class.
$(document).ready(function(){
$(function(){
$(".add-more").on("click", function(){
var list = $(".list");
var random_id = Math.floor(Math.random() * (99999 - 1 + 1)) + 1;
var child = document.createElement("li");
var text = document.createTextNode("Lorem Ipsum");
child.setAttribute("id", random_id);
child.appendChild(text);
list.append(child);
});
});
$(function(){
$(".list").on("click", "li", function(){
var id = $(this).attr("id");
$("#" + id).addClass("hidden");
console.log("This id: " + id + " is hidden");
});
});
});
a{
color: blue;
cursor: pointer;
}
ul{
margin-top: 20px;
padding: 0;
}
li{
list-style: none;
cursor: pointer;
}
li:hover{
color: red;
}
li + li{
margin-top: 20px;
}
li.hidden{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div>
<a class="add-more">Click me!</a>
</div>
<ul class="list">
<li id="0">Lorem Ipsum</li>
</ul>
document.getElementById(a_data.products[i].pid).style.display = 'none';
Let me assume that you are using jquery. Try something like this:
$(".plProductContainer.hide").hide();
or
var elementId = $(".plProductContainer.hide").attr("id");
$("#"+elementId).hide();
or
If your element is inside another element with id someId, then:
$("#"+someId).children()[i].hide(); //i is the loop counter that you have used to create element dynamically
or
$("#"+a_data.products[i].pid).hide(); //i is the loop counter that you have used to create element dynamically
It becomes easier if you already know the values of you loop counter i.e value of i, if you don't know that then you can also use selectors like nth child. Let me know if any of the above works, else I'll put up more selectors.

JQuery: create corresponding elements with same custom attrs

Fiddle here: http://jsfiddle.net/yv1vLhd9/
For whatever reasons, suppose I want to replace three dom elements with three others using JQuery, but I want to transfer one or more data attributes from the first elements onto their corresponding replacements.
Given the following HTML:
<div class='original' data-custom="dog"></div>
<div class='original' data-custom="cat"></div>
<div class='original' data-custom="sheep"></div>
And the following CSS:
div {
width: 100px;
height: 100px;
}
div:before {
content: attr(data-custom);
}
.original {
border: blue solid 1px;
}
.new {
border: pink solid 1px;
}
How can I make sure there is a new element with each of the custom data attributes?
For example:
$(document).ready( function(){
var $originalEl = $('.original')
var originalData = $originalEl.data('custom')
var replacement = '<div class="new" data-custom="' + originalData + '"></div>'
$originalEl.after(replacement).hide()
});
But this creates three new data-custom="dog" attributes.
You must use $.each for the element.
Starting after you declare $originalEl
$originalEl.each(function(){
// code here
})
Here is your code updated http://jsfiddle.net/yv1vLhd9/4/
http://jsfiddle.net/VixedS/wz95hh3r/1/
$(document).ready(function(){
$('.original').each(function(){
$(this).hide().clone().attr('class','new').show().appendTo('body');
})
});
jQuery provides a host of DOM manipulation methods that will help you achieve the desired input. As noted by some of the other answers, you'll need to traverse over the set of matched elements using $.each. In addition, rather than creating new elements from strings, you can use the .clone() method to:
clone the existing element
modify your new element
insert it after the original element
traverse to the original element
and finally hide the original element.
$(function () {
$('.original').each(function (idx, elem) {
$(elem)
.clone()
.removeClass('original')
.addClass('new')
.insertAfter($(elem))
.prev()
.hide();
});
});
div {
width: 100px;
height: 100px;
}
div:before {
content: attr(data-custom);
}
.original {
border: blue solid 1px;
}
.new {
border: pink solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='original' data-custom="dog"></div>
<div class='original' data-custom="cat"></div>
<div class='original' data-custom="sheep"></div>
API Method References:
jQuery.each()
.clone()
.removeClass()
.addClass()
.insertAfter()
.prev()
.hide()

Change CSS Property through JavaScript. (Uses ID's and Classes)

I'm trying to resize a panel using JavaScript to fit a small image into a panel, and struggling badly.
It's within the bold:
<body id="visCinemaTransRefund"><br>
<div id="content"><br>
<ul class="PayPanel" id="paymentDetails"><br>
Here's the CSS that needs modifying:
visCinemaTransRefund .PayPanel { width: 435px; }
How would I be able to modify with width of this panel?
I've also got a form I'm trying to resize within CSS:
visCinemaTransRefund FORM (width: 1005px;)
document.getElementById('paymentDetails').style.width = '1000px';
Have you tried using:
document.getElementById("paymentDetails").getElementsByClassName("PayPanel")[0].style.width="1000px"
Remember: getElementsByClassName return an array of elements, so using [0] you are indexing first element (and, of course, the only one).
Since getElementsById return a single elements, getElementsByClassName could be useless.
If you want to do this using CSS class :
HTML:
<div id="myDiv" class="medium"></div>
<button id="btn">Click me</button>
CSS:
#myDiv {
background-color: gray;
}
.medium {
height: 50px;
width: 50px;
}
.big {
height: 100px;
width: 100px;
}
JS:
document.getElementById("btn").onclick = function() {
var element = document.getElementById("myDiv"); // or document.getElementsByClassName("className")
if (element.className == "medium") {
document.getElementById("myDiv").className = "big";
} else {
document.getElementById("myDiv").className = "medium";
}
};
JSFIDDLE
Use the following code to change the width of tags by accessing HTML element from the DOM using getElement functions and setting width to it using setAttribute javaScript function.
document.getElementById("paymentDetails").setAttribute("style","width:500px;");
document.getElementById("visCinemaTransRefund").getElementsByTagName("form")[0].setAttribute("style","width:1000px;");
Using JavaScript:
document.getElementById('paymentDetails').style.width = '1000px';
Using JQuery:
$("paymentDetails").width(1000);
$("paymentDetails").css("width","1000px");

set a newly created div on top of the older divs

I have a bunch of divs inside a container. The position of the content divs is relative, because I want them to appear one below the other and their height is unknown.
These divs are created dynamically (appendchild) inside the container div. Now, each div appears on the end (bottom) of the stack but my requirement is that the divs have a "newest first" option too, that is, each new div appears on top, not on bottom of the content divs (if the user selects the "newest first" in the settings).
html:
<div class="container">
<div id="div1" class="content">aaa<br>aaa</div>
<div id="div2" class="content">bbb<br><br>bbb</div>
<div id="div3" class="content">ccc</div>
<div id="div4" class="content">ddd</div>
</div>
css:
.container {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
border: 1px solid red;
}
.content {
position: relative;
top: 0px;
left: 5px;
width: 200px;
height: auto;
border: 1px solid blue;
margin: 3px;
}
http://jsfiddle.net/jk559/1/
so I'd like the end-user visible order to be: div4, div3, div2, div1.
How can I achieve this? (css/js)
preferrably no jquery.
thanks in advice!
Pure css solution:
Use flexbox to achieve this.
.container {
display:flex;
flex-direction:column-reverse;
justify-content: flex-end;
align-content: flex-end;
}
Updated fiddle here.
Read more information here.
try this
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.setAttribute("id","div5");
theKid.setAttribute("class","content");
theKid.innerHTML = 'eee';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
Demo Fiddle http://jsfiddle.net/jk559/4/
You can easily do it with JQuery with the following function.
$('.container > div').each(function() {
$(this).prependTo(this.parentNode);
});
UPDATED FIDDLE
As you mentioned in the question, I will try to attain the expected output with the pure javascript.
You can insert content in the beginning simply using .prepend() .
$(".container").prepend("<div id='div5' class='content'>eee</div>");
Demo
JS FIDDLE UPDATED DEMO
Use prepend() to add as first child of an element
/* $( ".container" ).prepend( "Your div with id here" ); */
/* Example */
$( ".container" ).prepend( "<div id='div5' class='content' >div5 on top </div>" );
Take a look at this answer about reordering dom items.
Basically, you have to maintain a state that decides the ordering. When you insert items (see insertItem below) you append or prepend based on the state. When the user selects the newest first option (see newFirst below), you first reverse the dom elements and then flip the state so that subsequent insert happen at the right place.
var newFirst = false;
var list = document.getElementById('my-list');
function newFirst() {
var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
itemsArr.push(items[i]);
}
}
itemsArr.reverse();
for (i = 0; i < itemsArr.length; ++i) {
list.appendChild(itemsArr[i]);
}
newFirst = !newFirst;
}
function insertItem(content) {
var item = document.createElement("div");
item.setAttribute("class","content");
item.innerHTML = content;
if(newFirst) {
list.insertBefore(item, list.firstChild);
} else {
list.appendChild(item);
}
}
try this :
$("div[id*=div]").sort(function(a,b){
if(a.id > b.id) {
return -1;
} else {
return 1;
}
}).each(function() {
var elem = $(this);
$(".container").append(elem);
});
this will sort your divs inside container like this : div4, div3, div2, div1
if you want change the order to : div1, div2, div3, div4 just change if(a.id > b.id) to if(a.id < b.id)
you can add a link called change order then call this code when you click on it

Categories

Resources