Not able to append a paragraph to the image element - javascript

I made this favImages array and added some image objects to it. Then I am trying to append a paragraph element(removeButton) to each of them which will be triggered by clicking the images.
var favImages = new Object();
for (var i = 0; i < 5; i++) {
favImages[i] = document.getElementById("fav" + (i + 1));
}
var removeButton = document.createElement("p");
removeButton.id = "removebutton";
removeButton.innerHTML = "Remove Image";
for (var i = 0; i < 5; i++) {
var newImage = document.getElementById(favImages[i].id);
newImage.addEventListener("click", function() {
newImage.appendChild(removeButton)
}, false);
}

Don't use a loop. Use an event listener on the container and test what was clicked using event.target. You cannot add a child to an image
You COULD use a div, put the image as a background and the span to click as content
Anyway here are some examples
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("remove")) tgt.closest("div").remove()
})
#container div {
width: 200px
}
.remove {
float: right
}
<div id="container">
<div>
<span class="remove">X</span>
<img src="https://via.placeholder.com/150/0000FF/000888?text=image1" />
</div>
<div>
<span class="remove">X</span>
<img src="https://via.placeholder.com/150/FF00FF/000888?text=image2" />
</div>
<div>
<span class="remove">X</span>
<img src="https://via.placeholder.com/150/FF0000/000888?text=image3" />
</div>
</div>
From an array:
const images = [
"https://via.placeholder.com/150/0000FF/000888?text=image1",
"https://via.placeholder.com/150/FF00FF/000888?text=image2",
"https://via.placeholder.com/150/FF0000/000888?text=image3"
];
const container = document.getElementById("container");
container.innerHTML = images.map(img => `<div><span class="remove">X</span>
<img src="${img}" /></div>`).join("");
container.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("remove")) tgt.closest("div").remove()
})
#container div {
width: 200px
}
.remove {
float: right
}
<div id="container">
</div>

Related

Resizing 3 images with javascript

I need to resize 3 images with javascript. How can i do that without having an ID and without having possibility to add one?
I have tried this but i don t know how to select all images(i need to set the width to 50px).
let images=document.querySelector('img');
images.setAttribute("width",50);
Is document.querySelectorAll() what you're looking for? document.querySelectorAll() will select all elements matching a certain selector, not just the first.
In your case, it might be
let images=document.querySelectorAll('img');
images.forEach(img => img.setAttribute("width",50));
If you can't use CSS to change the image width pick up the images with querySelectorAll and then iterate over the node list of images and change the width of each one.
const images = document.querySelectorAll('img');
images.forEach(image => image.setAttribute('width', '50px'));
<img src="https://dummyimage.com/100x100/000/fff" />
<img src="https://dummyimage.com/100x100/000/fff" />
<img src="https://dummyimage.com/100x100/000/fff" />
You can do it with querySelectorAll
changeSize = () => {
let images = document.querySelectorAll('img');
for (let i = 0; i < images.length; i++) {
images[i].style.width = "100px";
}
}
originSize = () => {
let images = document.querySelectorAll('img');
for (let i = 0; i < images.length; i++) {
images[i].removeAttribute("style");
}
}
.images {
display: flex;
}
.images img {
margin: 1em 1em 0 0;
}
<button onclick="changeSize()">Change Size</button>
<button onclick="originSize()">Origin Size</button>
<div class='images'>
<img src="https://cdnp2.stackassets.com/b1284961a6fbcbcfabe6f69c2ae4219ff6daa5e0/store/opt/596/298/1ca89e578fc4e326fe08196758c1688929acc8c5eeb8572e2282628cad78/product_30565_product_shot_wide.jpg" />
<img src="https://cdnp2.stackassets.com/b1284961a6fbcbcfabe6f69c2ae4219ff6daa5e0/store/opt/596/298/1ca89e578fc4e326fe08196758c1688929acc8c5eeb8572e2282628cad78/product_30565_product_shot_wide.jpg" />
<img src="https://cdnp2.stackassets.com/b1284961a6fbcbcfabe6f69c2ae4219ff6daa5e0/store/opt/596/298/1ca89e578fc4e326fe08196758c1688929acc8c5eeb8572e2282628cad78/product_30565_product_shot_wide.jpg" />
</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

I want my image to disappear everytime I dblclick it

I have three image tags when I click one of the images in the webpage I don't it want to disappear it but when I dblclick I want it to disappear.
let img = document.querySelectorAll("img");
console.log(img)
let c = Array.from(img);
console.log(c);
c.forEach(function(imgs) {
imgs.addEventListener("click", function(e) {
let d = imgs;
d.addEventListener("dblclick", function(v) {
console.log(img)
// I want this eventlistener to make it disapear
document.querySelectorAll("image").innerHTML = "";
})
})
})
After I read your post again I have made some changes to my answer!
const imgs=document.querySelectorAll("img");
imgs.forEach(function(img){
img.addEventListener("dblclick", function(){
this.remove();
});
});
.box {
width: 220px;
padding: 20px;
background-color: #eee;
}
<div class="box">
Click the Image to remove it !
<br>
<img src="https://via.placeholder.com/200x200" style="width: 100%">
<br><br>
<img src="https://via.placeholder.com/200x200" style="width: 100%">
</div>
This works. Above answer works too.
let img = document.querySelectorAll("img");
console.log(img)
let c = Array.from(img);
console.log(c);
c.forEach(function(imgs) {
imgs.addEventListener("dblclick", function(e) {
imgs.style.display = "none";
})
})
<img src="https://via.placeholder.com/200x200" width=150 height=150>

Make div in div clickable with Javascript

Have a problem and can't get to solve it. Tried to use QuerySelectorAll and comma separating with GetElementsByClassName, but that didn't work, so I am wondering how to solve this problem.
I have this HTML:
<div class="area">Test title
<div class="some content" style="display: none">blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
<div class="area">
Test title
<div class="some content">
blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
JS:
function areaCollapse() {
var next = this.querySelector(".content");
if (this.classList.contains("open")) {
next.style.display = "none";
this.classList.remove("open");
} else {
next.style.display = "block";
this.classList.add("open");
}
}
var classname = document.getElementsByClassName("area");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', areaCollapse, true);
}
http://jsfiddle.net/1BJK903/nb1ao39k/6/
CSS:
.two {
position: absolute;
top: 0;
}
So now, the div with classname "area" is clickable. I positioned the div with class "two" absolute and now the whole div is clickable, except where this other div is. If you click on the div with classname "two", it doesn't work (it does not collapse or open the contents). How can I make this work, without changing the structure?
One way is using a global handler, where you can handle more than one item by checking its id or class or some other property or attribute.
Below snippet finds the "area" div and pass it as a param to the areaCollapse function. It also check so it is only the two or the area div (colored lime/yellow) that was clicked before calling the areaCollapse.
Also the original code didn't have the "open" class already added to it (the second div group), which mean one need to click twice, so I change the areaCollapse function to check for the display property instead.
function areaCollapse(elem) {
var next = elem.querySelector(".content");
if (next.style.display != "none") {
next.style.display = "none";
} else {
next.style.display = "block";
}
}
window.addEventListener('click', function(e) {
//temp alert to check which element were clicked
//alert(e.target.className);
if (hasClass(e.target,"area")) {
areaCollapse(e.target);
} else {
//delete next line if all children are clickable
if (hasClass(e.target,"two")) {
var el = e.target;
while ((el = el.parentElement) && !hasClass(el,"area"));
if (targetInParent(e.target,el)) {
areaCollapse(el);
}
//delete next line if all children are clickable
}
}
});
function hasClass(elm,cln) {
return (" " + elm.className + " " ).indexOf( " "+cln+" " ) > -1;
}
function targetInParent(trg,pnt) {
return (trg === pnt) ? false : pnt.contains(trg);
}
.area {
background-color: lime;
}
.two {
background-color: yellow;
}
.area:hover, .two:hover {
background-color: green;
}
.some {
background-color: white;
}
.some:hover {
background-color: white;
}
<div class="area">Test title clickable 1
<div class="some content" style="display: none">blablbala NOT clickable 1
</div>
<div class="two">This should be clickable too 1</div>
</div>
<div class="area">Test title clickable 2
<div class="some content">blablbala NOT clickable 2
</div>
<div class="two">This should be clickable too 2</div>
</div>
<div class="other">This should NOT be clickable</div>
You need to find your two elements while you're binding classname, and bind that as well.
var classname = document.getElementsByClassName("area");
for(var i=0; i < classname.length; i++){
classname[i].addEventListener('click', areaCollapse, true);
var twoEl = classname[i].getElementsByClassName("two")[0];
twoEl.addEventListener('click', function(e) { console.log('two clicked'); });
}
If you want to use jQuery:
$('.two').click(function(){
//action here
});

css apply style if parent width more than specific value

Want to apply css selectors if only parent element width more than specific value.
CSS must not use media query to implement this because no relation between viewport width and the parent div width.
Javascript is welcome but avoid continuous width check please.
Ex.
<style>
/* something like that div[width>400px] */
.parent div[width>400px]{
background:red;
}
</style>
<!--ok width is more than 400 so apply style to child div-->
<div class="parent" style="width:500px;">
<div>
</div>
</div>
<!--width is still less than 400 so don;t apply styles-->
<div class="parent" style="width:300px;">
<div>
</div>
</div>
The Resize event only works on the window element.
Vanilla JavaScript would be something like this.
var parentDivTriggrtWidth = 400;
var childDivClassNames = ["red", "blue"];
window.addEventListener("load", function(e){
var list = document.getElementsByClassName("parent");
for(var i=0; i<list.length; i++){
var parentDiv = list[i];
parentDiv.resizeParent = function(width){
if(typeof width!="undefined"){ this.style.width = width+"px"; }
var k = this.clientWidth > parentDivTriggrtWidth ? 1 : 0;
this.children[0].className = childDivClassNames[k];
// Debug only
this.children[0].innerHTML = "Parent Size: "+this.clientWidth+"<br />Class: "+this.children[0].className;
}
window.addEventListener("resize", function(e){ parentDiv.resizeParent(); },false);
parentDiv.resizeParent();
}
},false);
Look at the snippet in "fullpage"
var parentDivTriggrtWidth = 400;
var childDivClassNames = ["red", "blue"];
window.addEventListener("load", function(e){
var list = document.getElementsByClassName("parent");
for(var i=0; i<list.length; i++){
var parentDiv = list[i];
parentDiv.resizeParent = function(width){
if(typeof width!="undefined"){ this.style.width = width+"px"; }
var k = this.clientWidth > parentDivTriggrtWidth ? 1 : 0;
this.children[0].className = childDivClassNames[k];
// Debug only
this.children[0].innerHTML = "Parent Size: "+this.clientWidth+"<br />Class: "+this.children[0].className;
}
window.addEventListener("resize", function(e){ parentDiv.resizeParent(); },false);
parentDiv.resizeParent();
}
},false);
.parent {
border: 3px solid #aaaaaa;
}
.parent div {
width: 200px;
height: 200px;
color: white
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
<h3>width 500px (resize by JavaScript)</h3>
<div id="p1" class="parent" style="width:500px;">
<div></div>
</div>
<button type="button" onclick="document.getElementById('p1').resizeParent(800)">Resize +</button>
<button type="button" onclick="document.getElementById('p1').resizeParent(200)">Resize -</button>
<button type="button" onclick="document.getElementById('p1').resizeParent(500)">Reset</button>
<hr />
<h3>width 100% (resize window)</h3>
<!--width is still less than 400 so don;t apply styles-->
<div id="p2" class="parent" style="width:100%;">
<div></div>
</div>
jQuery is an option :
$( document ).ready(function() {
if ($(".parent").width() > 700) {
$('.parent').css("background-color", "red");
}
});
if i got you right...
JQuery:
$(document).ready(function(){
var ParentWidth = $('.parent').width();
if (ParentWidth > 400) {
$('.parent').addClass('newstyle');
}
});
CSS:
.newstyle
{
background: red;
/*** add more css ***/
}
i Recommends you to use class because you can add more css to the class later.

Categories

Resources