How To Apply jQuery CSS Selector - javascript

I am trying to apply jquery selector on the div which are dynamically created from javaScript Loop
Div's are created from for loop assign class to each div
minus = textbox1 - textbox2;
var count = 0;
var a;
for (x = textbox1; x >= minus; x--) {
a = count++;
$('body').append('<div class="drag' + a + '" >' + x + '</div>');
}
now I am trying to add the css selector on these but it is not working
var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
var i = 0;
$(".drag").each(function(){
$(this).css("color",colors[i]);
if(i == colors.length-1)
{
i = 0;
}
else
{
i++;
}
});
the complete code is given below
$("#submitBtn").click(function(){
var x;
var minus;
var textbox1= new Number($("#value1").val());
var textbox2= new Number($("#value2").val());
var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
var i = 0;
$(".drag").each(function(){
$(this).css("color",colors[i]);
if(i == colors.length-1)
{
i = 0;
}
else
{
i++;
}
});
minus=textbox1-textbox2;
var count=0;
var a;
for(x=textbox1;x>=minus;x--){
a=count++;
$('body').append('<div class="drag'+a+'" >' +x+ '</div>');
}
});

You can use attribute starts with selector like following.
var colors = ["#42ae18", "#eabc00", "#147cc4", "#FF6EB4", "#ed4329", "#8d33aa", "#00b971", "#e9681b", "#a2b3d4", "#0b863c", "#eabc00", "#7027a5", "#c83131", "#00a1de", "#0bc1b6", "#FF6EB4", "#10a0b6", "#FF6EB4", "#eedfd3", "#362819", "#FFD700"];
var i = 0;
$("[class^=drag]").each(function () { //change selector here
$(this).css("color", colors[i]);
if (i == colors.length - 1) {
i = 0;
}
else {
i++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="drag0">!!!!!</div>
<div class="drag1">!!!!!</div>
<div class="drag2">!!!!!</div>
<div class="drag3">!!!!!</div>
<div class="drag4">!!!!!</div>
<div class="drag5">!!!!!</div>
<div class="drag6">!!!!!</div>
<div class="drag7">!!!!!</div>
<div class="drag8">!!!!!</div>

Related

Javascript navigation with array

I'm trying to make a navigation that chagnes the background of a div using the array data.
It isn't working like I would want it.
I'm trying to use if inside addEventListener with 'click' function.
var designNextBg = document.getElementById('js-nextbg');
var designBg = document.getElementById('js-designBg');
var designBgArray = [
'url(images/ipb.png)',
'url(images/ipg.png)',
'url(images/ipr.png)',
'url(images/ipw.png)',
'url(images/ipy.png)'
];
var positionBg = document.getElementById('js-positionBg');
var i = 0;
designNextBg.addEventListener('click', function(e) {
if (i = 0) {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else if (i = 4) {
designBg.style.backgroundImage = designBgArray[i];
i = 0;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
};
});
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<a id="js-prevbg" class="angle-buttons"><i class="fa fa-angle-left"></i></a>
<a id="js-nextbg" class="angle-buttons"><i class="fa fa-angle-right"></i></a>
</p>
</div>
</div>
your code is way to complicated. I've added two ways to deal with i and keep it inside the bounds. For once, you can do this in the click-handler (currently commented out), or you can just continuously increment/decrement there and compute the actual index inside the array with a oneliner.
var designBg = document.getElementById('js-designBg');
var designBgArray = [
'url(images/ipb.png)',
'url(images/ipg.png)',
'url(images/ipr.png)',
'url(images/ipw.png)',
'url(images/ipy.png)'
];
var positionBg = document.getElementById('js-positionBg');
var i = 0;
var nextButton = document.getElementById('js-nextbg');
var prevButton = document.getElementById('js-prevbg');
nextButton.addEventListener('click', function(e) {
//if(++i === designBgArray.length) i=0;
++i;
updateView();
});
prevButton.addEventListener('click', function(e) {
//if(--i < 0) i += designBgArray.length;
--i;
updateView();
});
function lz(nr){//a simple leading zero function
return String(nr).padStart(2, 0);
}
funciton updateView(){
var len = designBgArray.length;
//get i back into the boundaries
//you could also take care of that in the click-handler
//but this way, it's all in one place
var index = i%len + (i<0? len: 0);
designBg.style.backgroundImage = designBgArray[index];
positionBg.textContent = lz(index+1) + "/" + lz(len);
}
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<a id="js-prevbg" class="angle-buttons"><i class="fa fa-angle-left"></i></a>
<a id="js-nextbg" class="angle-buttons"><i class="fa fa-angle-right"></i></a>
</p>
</div>
</div>
This code works for 'NEXT' button with changing background colours replace backgroundImage as per requirement
var designNextBg = document.getElementById('js-nextbg');
var designBg = document.getElementById('js-designBg');
var designBgArray = [
'red',
'green',
'blue',
'yellow',
'cyan'
]; var positionBg = document.getElementById('js-positionBg');
var i = 0;
designNextBg.addEventListener('click', function(e) {
if (i == 0) {
designBg.style.background = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else if (i == 4) {
designBg.style.background = designBgArray[i];
i = 0;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else {
designBg.style.background = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
};
});
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<input type ='button' value ='NEXT' id="js-nextbg" class="angle-buttons">
</p>
</div>
</div>
designNextBg.addEventListener('click', function(e) {
if (i = 0) {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else if (i = 4) {
designBg.style.backgroundImage = designBgArray[i];
i = 0;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
};
});
Here, inside if you must give == or === for comparison. = means assignment operator which always returns true. So i=0 returns true and always the first condition gets passed. So it returns 1. So it changes the span to 01/05.
Taking into account your code and answer posted by Thomas I would provide a working example instead of blank screen and nonexistent background.
Introduced minor code improvements for easier reading, service logic isolation and less letters.
/**
* List of random images
* #type {Array}
*/
var designBgArray = [
'https://picsum.photos/200/300',
'https://picsum.photos/201/300',
'https://picsum.photos/202/300',
'https://picsum.photos/203/300',
'https://picsum.photos/204/300'
];
var getEl = function(id) {
return document.getElementById(id);
},
addClick = function(el, fn) {
el.addEventListener('click', fn);
},
lz = function(nr) {
return String(nr).padStart(2, 0);
};
var designBg = getEl('js-designBg'),
positionBg = getEl('js-positionBg'),
nextButton = getEl('js-nextbg'),
prevButton = getEl('js-prevbg');
var render = function() {
var len = designBgArray.length,
index = i % len + (i < 0 ? len : 0);
console.log('Rendering "i"', i);
designBg.style.backgroundImage = 'url('+designBgArray[index]+')';
positionBg.textContent = lz(index+1) + "/" + lz(len);
};
var i = 0;
render(); // Initial background set (if blank bg is not applicable)
addClick(nextButton, function(e) {
i++;
if (i === designBgArray.length + 1) {
i = 0;
}
render();
});
addClick(prevButton, function(e) {
i--;
if (i < 1) {
i = designBgArray.length;
}
render();
});
.angle-buttons, #js-positionBg {
background-color: white;
}
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<a id="js-prevbg" class="angle-buttons"><</a>
<a id="js-nextbg" class="angle-buttons">></a>
</p>
</div>
</div>

Appending a button using Javascript without using the createElement method

<script>
var i=0;
var j="";
function app() {
j+=document.getElementById("demo").innerHTML="<button type='button'>Btn+i</button>";
}
</script>
<button type="button" onclick="app()">Add</button>
<div id="demo">
</div>
I am trying to append a button in the div tag every time user clicks add button.
Also I want the added button to be displayed like : Btn 1, Btn2,
Btn3..
A simple concatenation of #demo content and incrementation of a var i:
var i = 0;
function app() {
document.getElementById("demo").innerHTML += "<button type='button'>Btn " +
++i + "</button>";
}
<button type="button" onclick="app()">Add</button>
<div id="demo"></div>
You need to append HTML
var s = 0;
function app(){
s++;
var strHTML = "<button>Btn"+ s+"</button>"
document.getElementById('test').insertAdjacentHTML( 'beforeend', strHTML );
}
See this http://jsfiddle.net/euQ5n/226/
Or make it a little more readable.
<script>
var i = 0;
var j = "";
function makeButton(index) {
var $button = document.createElement('BUTTON');
$button.innerHTML = 'Button ' + index;
$button.onclick = function() {
alert('You clicked button:' + index);
};
return $button;
}
function onAddButtonClick() {
document.getElementById("demo").appendChild(makeButton(i));
i++; // increase number for next time;
}
</script>
<button type="button" onclick="onAddButtonClick()">Add</button>
<div id="demo">
</div>
var i1 = 0;
function app1()
{
var div = document.createElement('div');
div.innerHTML = "<button type='button'>Btn " + (++i1) + "</button>";
for (var child = 0; child < div.childNodes.length; child) {
document.getElementById("demo1").append(div.childNodes[child]);
}
}
var i2 = 0;
function app2() {
document.getElementById("demo2").innerHTML += "<button type='button'>Btn " +
++i2 + "</button>";
}
var d1s = new Date().getTime();
for (var j1 = 0; j1 < 1000; j1++) {
app2();
}
var d1e = new Date().getTime();
console.log((d1e - d1s) / 1000);
var d2s = new Date().getTime();
for (var j2 = 0; j2 < 1000; j2++) {
app1();
}
var d2e = new Date().getTime();
console.log((d2e - d2s) / 1000);
<div id="demo1"></div>
<div id="demo2"></div>
concatenation with innerHtml += is very slow
You need to change .innerHtml += ...
And increase i
var i=0;
function app()
{
j+=document.getElementById("demo").innerHTML+="<button type='button'> Btn"+i+"</button>";
i++;
}
<button type="button" onclick="app()">Add</button>
<div id="demo">
</div>

Toggling background color of div

Title, my only problem is that when I've created all elements on my page, and clicked all of them, my page looks like a chess board.
I can only "toggle" the background color of half too. So it's not only that they don't change color on the first click, they don't change at all.
This is my Javascript:
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div" + i);
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
for (let i = 0; i < 10; i++) {
$('div' + i).click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
}
document.getElementById("page").appendChild(itemContainer);
}
I made a JSFiddle for you who want it.
I've seen a few other questions about how to toggle the color of backgrounds, but none of them have the same problem as me.
You inserted your second loop into the first one, every second i got skipped. And probably was able to change your divs up to i=18
JSFiddle
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div" + i);
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
document.getElementById("page").appendChild(itemContainer);
}
for (let i = 0; i < 10; i++) {
$('div' + i).click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
}
Edit: You could simply put the content of your second loop into the first loop, to simplify your code a bit.
You don't need 2 loops try that
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
document.getElementById("page").appendChild(itemContainer);
$('#div' + i).click(function() {
alert("here");
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
}
fiddle example
You were close, missing "#" of id element
$('div' + i).click(function() {
$('#div' + i).click(function() {
and you have inserted the second loop inside first one
https://jsfiddle.net/snbtchph/
Your selector at line 8 of your JavaScript is missing the # so the jQuery is looking for <div0>, <div1>, <div2>..., and, your line 2 of JavaScript is var itemContainer = document.createElement("div" + i); which actual creating elements div0, div1....
And since you are using jQuery , I have also revised some code to use it instead of native JavaScript: https://jsfiddle.net/xfr496p6/5/
I have also added css .item { display: inline-block; } to makes the elements placed in a row.
There are a few problems with your code:
var itemContainer = document.createElement("div" + i);
Creating non-existant elements like <div1> is impossible, remove the iterator.
for (let i = 0; i < 10; i++) {
jQuery's .click() doesn't need a for loop, but adds the event listener to every case, this is not needed.
document.getElementById("page").appendChild(itemContainer);
Apply this directly in after the .innerHTML
In addition, you seem to randomly use ES6, jQuery, and VanillaJS through your entire codebase, I'd like to advise you to be consistant with how you write your applications.
I've updated your fiddle with the working changes.
https://jsfiddle.net/xfr496p6/8/
Updated javascript:
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!" + i;
document.getElementById("page").appendChild(itemContainer);
}
$('div').click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
Why do you have 2 nested loops?
try this
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div" + i);
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
document.getElementById("page").appendChild(itemContainer);
}
for (let i = 0; i < 10; i++) {
$('div' + i).click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
}
JSFIDDLE
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div" + i);
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
$(itemContainer).click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
document.getElementById("page").appendChild(itemContainer);
}

How to ssign Variable with div element's name

So I got multiple divs with different images embedded. Each one has its unique name attributes. I'm trying to apply the hover effect to each divs by changing the image source. I don't want to write multiple scripts, rather I'm trying to write a just one block of script that would effect every div.
<div id="div1" >
<img id="img1" name="img1" src="img1_up.jpg" />
</div>
<div id="div2">
<img id="img2" name="img2" src="img2_up.jpg" />
</div>...and so on
Now here is the script that I currently have for the rollover effects
<script>
var var1 = document.getElementById("div1");
var1.addEventListener("mouseover", changeImage1);
var1.addEventListener("mouseout", restoreImage1);
function changeImage1() {
document.getElementById("img1").src = "img1_ro.jpg";
}
function restoreImage1() {
document.getElementById("img1").src = "img1_up.jpg";
}
var var2 = document.getElementById("div2");
var2.addEventListener("mouseover", changeImage2);
var2.addEventListener("mouseout", restoreImage2);
function changeImage2() {
document.getElementById("img2").src = "img2_ro.jpg";
}
function restoreImage2() {
document.getElementById("img2").src = "img2_up.jpg";
}...and so on
</script>
I would like to use the name attributes from each images to create dynamic code to apply to all images. Here is what I have in mind but not sure the exact way to write it. PLEASE HELP
...
var dynamicVar = ????
dynamicVar.addEventListener("mouseover", changeImage();
dynamicVar.addEventListener("mouseout", restoreImage();
function changeImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_ro.jpg";
}
function restoreImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_up.jpg";
}
You can use loop to add event, don't need to specify id for each div:
var inputs = document.getElementsByTagName("div");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf('div') >= 0) {
inputs[i].addEventListener("mouseover", changeImage);
inputs[i].addEventListener("mouseout", restoreImage);
}
}
function changeImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_ro.jpg";
}
function restoreImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_up.jpg";
}
See on fiddle: Link
try this
var parent = document.getElementById("parent");
var childs = parent.getElementsByTagName('div');
for (var i = 0; i < childs.length; i++) {
(function () {
var e = childs[i];
e.addEventListener("mouseover", function () {
changeImage(e);
});
e.addEventListener("mouseout", function () {
restoreImage(e);
});
}());
}
function changeImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
alert(imgs[i].id);
}
}
function restoreImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = img_ro;
}
}
you can check this fiddle

how to get the image path in same way as item.src?

I am using freewall.js from http://vnjs.net/www/project/freewall/
The images would be dynamic. So html will have:
<div class="brick">
<img src="" width="100%">
</div>
JS
$(".free-wall .brick img").each(function(index, item) {
item.src = "images/" + (++index) + ".jpg";
});
The thing I want to do is to prepend a few more images to the freewall.
var temp = '<div class="brick"><img src="" width="100%"></div>';
$(".add-more").click(function() {
for (var i = 0; i < 4; ++i) {
wall.prepend(temp);
}
wall.fitWidth();
});
When the add-more button is clicked, 4 images will be prepended. the problem is how to append the image path in same way?
help appreciated!
Try
var temp = '<div class="brick"><img src="" width="100%"></div>';
$(".add-more").click(function () {
var start = $(".free-wall .brick img").length + 1;
for (var i = 0; i < 4; ++i) {
$(temp).prependTo(wall).find('img').attr('src', "images/" + (start + i) + ".jpg")
//or wall.prepend('<div class="brick"><img src="images/' + (start + i) + '.jpg" width="100%"></div>');
}
wall.fitWidth();
});
Update:
$(".add-more").click(function () {
var start = $("#freewall .brick img").length + 1,
$imgs = $(),
$img, loadcounter = 0;
for (var i = 0; i < 4; ++i) {
$img = $(temp).appendTo('.free-wall').find('img').attr('src', 'http://placehold.it/64&text=' + (start + i) + '.jpg').hide();
$imgs = $imgs.add($img);
}
$imgs.on('load error', function () {
loadcounter++;
if (loadcounter == 4) {
$imgs.show();
wall.fitWidth();
}
}).filter(function(){
return this.complete
}).trigger('load')
});
Demo: Fiddle
Try this,
$(".add-more").click(function() {
for (var i = 0; i < 4; ++i) {
src="images/"+(i+1)+".jpg";
wall.prepend('<div class="brick"><img src="'+src+'" width="100%"></div>');
}
wall.fitWidth();
});

Categories

Resources