How to clone, modify (increment some elements) before appending using jQuery? - javascript

I have an element that contains multiple elements inside it, what I need is to clone the element, but on every "new" element, I need to increment an element (the object number -see my script please-)
In the script I'm adding I need (every time I click on the button) to have : Hello#1 (by default it's the first one) but the first click make : Hello#2 (and keep on top Hello#1) second click = Hello#1 Hello#2 Hello#3 ... We need to keep the oldest hellos and show the first one.
var count = 1;
$(".button").click(function(){
count += 1;
num = parseInt($(".object span").text());
$(".object span").text(count);
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
});
.object{
width:100px;
height:20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>

You just have to change a little:
var count = 1;
$(".button").click(function() {
count += 1;
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(count); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
and if you want to simplify this more use this:
$(".button").click(function() {
var idx = ++$('.object').length; // check for length and increment it with ++
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(idx); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>

Use the following function, this is more modular and you can use it to update the count if you remove one of the elements
function updateCount() {
$(".object").each(function(i,v) {
$(this).find("span").text(i+1);
});
}
$(".button").click(function() {
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
updateCount();
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>

Related

JavaScript Get Selected Item's TextContent

I want to make a program that write out the textContent of the item that has clicked. For some reason this program only get the last element's content. Any idea what should I change inside the for loop?
var emailname = document.querySelectorAll(".name");
var gSenderName = document.getElementById('sname');
$('.name').click(function() {
for (var i = 0; i < emailname.length; i++) {
const sendername = emailname[i].textContent;
gSenderName.textContent = sendername;
}
});
.name:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>
<div>Selected:
<div id="sname"></div>
</div>
You do not need the loop here at all. You can simply get the currently clicked element's text by using this object. I will also suggest you not mix up vanilla JS and jQuery unnecessarily:
var gSenderName = $('#sname');
$('.name').click(function(){
gSenderName.text($(this).text());
});
.name:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>
<div>Selected:
<div id="sname"></div>
</div>
The loop runs and sets the text content of each item one after the other. Because each override the other, you always get the last one.
Just set the text content of the element that was clicked:
var gSenderName = document.getElementById('sname');
$('.name').click(e => {
gSenderName.textContent = e.target.textContent;
});
.name:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>
<div>Selected:
<div id="sname"></div>
</div>

How to remove random div js

http://prntscr.com/p9u6f9
I create random divs using:
let div1 = 'div_list';
let div2 = div1 + [Math.floor(Math.random()*24)];
node.setAttribute('id', div2);
And I want remove div using button, but how can I remove this, not having ID? Because the ID is random.
function remove() {
console.log(div);
let remove = document.getElementById(??????????);
remove.remove();
}
Add an eventListener upon the creation of the node and call remove with the generated id :
let div1 = "div_list";
let div2 = div1 + [Math.floor(Math.random() * 24)];
node.setAttribute("id", div2);
node.addEventListener("click", () => remove(div2)); // add the event listener for the button of deletion if you're creating it with the div
function remove(id) {
console.log(id);
let remove = document.getElementById(id);
remove.remove();
}
Just try this example, it's 100% working.
function randRemove() {
var divCount = 5;
var randNumber = Math.floor(Math.random() * divCount) + 1;
var randSelect = document.getElementById("div-" + randNumber);
randSelect.remove();
alert("Div Removed: " + "div-" + randNumber);
}
.just-style {
display: inline-block;
width: 300px;
height: 100px;
margin: 20px;
}
<button id="randRemove" onclick="randRemove()">Remove Random Div</button>
<div id="main-div">
<div id="div-1" class="just-style" style="background-color: red;"></div>
<div id="div-2" class="just-style" style="background-color: blue;"></div>
<div id="div-3" class="just-style" style="background-color: aqua;"></div>
<div id="div-4" class="just-style" style="background-color: violet;"></div>
<div id="div-5" class="just-style" style="background-color: forestgreen;"></div>
<!--AND MORE DIV ... -->
</div>
Enjoy and good luck =D

Why does one calculation for my onClick get applied to all elements that I'm looping through

Currently doing some exercise for CSS/Javascript animation. I'm attempting to make a Carousel slider from scratch.. I have 4 divs with 550px in width nested in a wrapper of 2200px, which is then nested in a 550px wrapper with overflow hidden.
I then created 4 LI's that I want to make clickable so that it'll translate the wrapper -550*I degrees for every LI.
I performed a queryselectorall to get all the li's, looped through it with a for loop, and created a function that should apply onclick functionality for each LI button.
The issue that I'm running into is that the first calculation of this transform property is applied to all LI's (the 550 * i for [1] [2] and [3] aren't applied).
Here's the HTML that I'm currently using.
<div id="container">
<div id="wrapper">
<div id="itemOne" >
</div>
<div id="itemTwo">
</div>
<div id="itemThree">
</div>
<div id="itemFour">
</div>
</div>
</div>
<ul>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
</ul>
The Javascript
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll(".button");
for(var i = 0; i < buttons.length; i++){
var curBut = buttons[i];
curBut.addEventListener("click", function(){
wrapper.style[transformProperty] = 'translate3d(-'+((0-i) * 550) +'px,0,0'
})
console.log(((0-i) * 550));
}
console.log(buttons);
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++){
if(typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
If anyone could explain why the function isn't applying the different changes for the wrapper for each LI, that'd be great! Thanks!!
The global variable i is not copied into each listener, it's shared between the listeners. When you click a button, i is already set to its final value which is 4. As a possible workaround you could override the global variable with a local variable, and get the index on click using indexOf :
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
var curBut = buttons[i];
curBut.addEventListener("click", function() {
var i = Array.prototype.indexOf.call(buttons, this);
wrapper.style[transformProperty] = 'translate3d(-' + (i * 260) + 'px,0,0)';
});
}
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++) {
if (typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
#container {
overflow: hidden;
background: gray;
margin-bottom: 1em;
width: 260px;
height: 100px;
}
#wrapper {
width: calc(4 * 260px);
height: 100px;
}
#wrapper div {
padding: 0 1em;
width: calc(260px - 2em);
line-height: 100px;
height: 100px;
float: left;
color: white;
font-size: 3em;
font-weight: bold;
text-align: center;
}
<div id="container">
<div id="wrapper">
<div id="itemOne">1</div>
<div id="itemTwo">2</div>
<div id="itemThree">3</div>
<div id="itemFour">4</div>
</div>
</div>
<div>
<button type="button">button 1</button>
<button type="button">button 2</button>
<button type="button">button 3</button>
<button type="button">button 4</button>
</div>

Using array to change colours

hi I'm trying to use an array to change colors. I want to Make a function called ChangeColor(num) with an argument for numbers and Use the function to change the color of the box so when the button is clicked on, it calls on the function and sends the correct number so that "box.style.backgroundColor = arrName[num];" Heres what i got so far.
<!DOCTYPE html>
<html>
<head>
<style>
#box {
width:200px;
height:200px;
background-color:black;
}
</style>
</head>
<body>
<div id="group">
<button id="blue">Blue</button>
<button id="red">Red</button>
<button id="green">Green</button>
</div>
<div id="box"></div>
<script type="text/javascript">
var colors = ["blue","red","green"];
var blue = document.getElementById("blue");
var red = document.getElementById("red");
var green = document.getElementById("green");
var box = document.getElementById("box");
var numclicks = 0;
blue.addEventListener("click", function() {
if(numclicks == 0) {
box.style.backgroundColor = colors[0];
}
});
red.addEventListener("click", function() {
if(numclicks == 0) {
box.style.backgroundColor = colors[1];
}
});
green.addEventListener("click", function() {
if(numclicks == 0) {
box.style.backgroundColor = colors[2];
}
});
</script>
</body>
</html>
You can simply attach an event listener to the buttons within #group and set the background-color of the #box the id of the clicked button:
var box = document.querySelector('#box');
document
.querySelectorAll('#group button')
.forEach(function (el) {
el.addEventListener('click', function () {
box.style.backgroundColor = el.id;
});
});
#box {
width:200px;
height:200px;
background-color:black;
}
<div id="group">
<button id="blue">Blue</button>
<button id="red">Red</button>
<button id="green">Green</button>
</div>
<div id="box"></div>
standard function
const colors = ["blue","red","green"];
const defaultColor = "white"; // if you want for kill errors
function changeColor(num){
document.querySelector("#box").style.backgroundColor = colors[num]||defaultColor
}
then you can added onclick events to buttons like this
<div id="group">
<button onclick="changeColor(0)" id="blue">Blue</button>
<button onclick="changeColor(1)" id="red">Red</button>
<button onclick="changeColor(0)" id="green">Green</button>
</div>
or with attributes like (but keep buttons elements depend to same order of array colors names)
html
<div id="group">
<button number="0" id="blue">Blue</button>
<button number="1" id="red">Red</button>
<button number="2" id="green">Green</button>
</div>
javascript
document.querySelectorAll("#group button").forEach((button)=>{
button.addEventListener('click', function () {
changeColor(button.getAttr("number"));
});
});
The other solutions use practices that are currently considered better. Here is a solution that includes the unnecessary array.
function changeColor(num) {
var colors = ['blue', 'red', 'green'];
document.getElementById('box').style.backgroundColor = colors[num];
}
#box {
width: 200px;
height: 200px;
background-color: black;
}
<div id="group">
<button id="blue" onclick="changeColor(0)">Blue</button>
<button id="red" onclick="changeColor(1)">Red</button>
<button id="green" onclick="changeColor(2)">Green</button>
</div>
<div id="box"></div>

Change CSS of div when clicking on a button

Is it possible to change the background image of a div when a button outside of the div is selected?
e.g.
HTML
<div id="change"></div>
<div id="buttons">
<button class="button1">this</button>
<button class="button2">that</button>
<button class="button3">there</button>
<button class="button4">then</button>
</div>
CSS
#change{
background-image: url("this.jpg")
}
Desired effect when clicking button 2 (same for each button; 3 = there.jpg, 4 = then.jpg)
#change{
background-image: url("that.jpg")
}
Using javascript you can set the backgroundImage. Using jQuery you'd use $.css('background-image');
You could also use JS/jQuery to add a class to the element, and you can set the background-image in CSS for that class.
document.getElementById('button').addEventListener('click',function() {
document.getElementById('change').style.backgroundImage = 'url(https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg)';
})
#change {
background: #eee;
width: 600px;
height: 375px;
}
<button id="button">button</button>
<div id="change"></div>
document.getElementById('button').addEventListener('click',function() {
document.getElementById('change').classList.add('bg');
})
#change {
background: #eee;
width: 600px;
height: 375px;
}
#change.bg {
background-image: url(https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg)
}
<button id="button">button</button>
<div id="change"></div>
You can do this but it will require JavaScript:
Your HTML:
<div id="buttons">
<button class="button1" onclick="changeBG('image1.jpg')">this</button>
<button class="button2" onclick="changeBG('image2.jpg')">that</button>
<button class="button3" onclick="changeBG('image3.jpg')">there</button>
<button class="button4" onclick="changeBG('image4.jpg')">then</button>
</div>
<script>
function changeBG(image) {
var urlString = "url(" + image + ")";
document.getElementById('change').style.backgroundImage = urlString;
}
</script>
This is not the prettiest way to do this but it should accomplish getting you started.
This is what you need in jQuery :D
$('#buttons button').on('click',function() {
var val = $(this).text();
$('#change').css('background-image','url('+val+'.jpg)');
});
put the script inside $(document).ready(function() {

Categories

Resources