Embed Button on image using DOM - javascript

I want to embed button on image using dom. There will be multiple images having multiple button on it which deletes image on click.
I want something like this - JSFiddle
Code I tried:
var div = document.createElement('div');
var parent = document.getElementById('images1');
var btn = document.createElement('input');
btn.type = 'button';
btn.className="multiple",
div.style.cssText = "position: relative; margin-bottom: 10px ; width: 100%;";
btn.style.cssText = " position: absolute; top: 10px; background-image: url(http://totravelistolearn.in/wp-content/themes/travel/images/cross-512.png); width: 20px; height: 20px; border: 0; background-size: 100%; background-repeat: no-repeat;";
//textbox.placeholder = 'Add details about attached Image';
//btn.value = "Remove";
btn.onclick = removeImage;
img = new Image();
img.style.display = 'block';
img.className = 'hi1';
img.style.cssText = 'height: 100px; width: 100px; position: relative;';
img.src = results[i];
div.appendChild(div);
div.appendChild(img);
div.appendChild(btn);
Function to remove image -
function removeImage(){
$$(this).prev("img").remove();
$$(this).remove();
div.parentNode.removeChild(div);
}

you need to use class instead of id, also closest() will do the job for you: DEMO
$('.myButton').click(function(){
$(this).closest('.MyImage').remove();
});

On button click, you can remove the div that contains that image and button, like this :
$('.myButton').on('click', function() {
$(this).closest('div.MyImage').remove();
});
As, I wouldn't advice using same id on multiple elements in one page, I have changed them to classes and then worked through that. I'd suggest you do the same, if your use-case allows you to.
Here is the updated Fiddle

As I Understand , written this code please check once.
function createItem() {
div = document.createElement("div");
div.setAttribute("class", "parent");
image = document.createElement("img");
image.src = "http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg";
image.style.width = "100%";
btn = document.createElement("button");
btn.setAttribute("class", "MyButton");
var textnode = document.createTextNode("X");
btn.appendChild(textnode);
btn.style.position = "absolute";
btn.style.left = "10px";
btn.style.left = "10px";
div.appendChild(image);
div.appendChild(btn);
div.style.width = "100px";
div.style.height = "100px";
div.style.overflow = "hidden";
div.style.marginBottom = "10px";
document.body.appendChild(div);
}
createItem();
createItem();
createItem();
parentDiv = document.getElementsByClassName("parent");
console.log(parentDiv.length);
buttonObject = document.getElementsByClassName("MyButton");
for (var i = 0; i < buttonObject.length; i++) {
buttonObject[i].id = i;
buttonObject[i].onclick = function() {
myId = this.getAttribute("id");
parentDiv[myId].remove()
}
}

Related

change border of contenteditable div element when focus using javascript

I am using javascript for the editable div element.
var div = document.getElementById('htmlelement');
var ele = document.createElement('div');
ele.setAttribute('id','inputelement');
ele.style.display = 'inline-block';
ele.style.border = 'none';
ele.style.minHeight = '100px';
ele.style.maxHeight = '100px;'
ele.style.padding = '10px';
ele.style.fontSize = '12px';
ele.style.color = 'blue';
ele.setAttribute('contentEditable','true');
div.appendChild(ele);
ele.focus();
Now after focus black border shows over the div area automatically.
I want to remove and change that border color, but I think CSS will not work for this. because div element is dynamically created by javascript.
is any way to remove that black border or change that border color.
i am tryijng to use css but not working because of dynamic element creation
like,
[contenteditable] {
outline: 0px solid transparent;
}
When you talk about "border" you mean "outline"? You can just set it to none.
var div = document.getElementById('htmlelement');
var ele = document.createElement('div');
ele.id = 'inputelement';
ele.style.display = 'inline-block';
ele.style.border = 'none';
ele.style.minHeight = '100px';
ele.style.maxHeight = '100px;';
ele.style.padding = '10px';
ele.style.fontSize = '12px';
ele.style.color = 'blue';
ele.setAttribute('contentEditable', 'true');
div.appendChild(ele);
ele.focus();
div[contenteditable] {
outline: none;
}
<div id="htmlelement"></div>

Space between divs seem to change

I'm trying to create a space between the black keys:
I've tried margin-left, but it still stay the same. My css is dynamically generated using javascript:
//Append inside a pre-made window
this.keyboardDiv = document.createElement("div");
var attr = document.createAttribute("id");
attr.value = "mkbKeyboardDiv";
this.keyboardDiv.setAttributeNode(attr);
widgetWindow.getWidgetBody().append(this.keyboardDiv);
.......
var mkbKeyboardDiv = this.keyboardDiv;
mkbKeyboardDiv.style.display = 'inline';
mkbKeyboardDiv.style.visibility = 'visible';
mkbKeyboardDiv.style.border = '0px';
mkbKeyboardDiv.style.width = '300px';
mkbKeyboardDiv.style.top = '0px';
mkbKeyboardDiv.innerHTML = '';
mkbKeyboardDiv.innerHTML = ' <div id="keyboardHolder2"><table class="white"><tbody><tr id="myrow"></tr></tbody></table><table class="black"><tbody><tr id="myrow2"></tr></tbody></table></div>'
var keyboardHolder2 = docById('keyboardHolder2');
keyboardHolder2.style.bottom = '10px';
keyboardHolder2.style.left = '0px';
keyboardHolder2.style.height = '145px'
keyboardHolder2.style.width = '700px';
keyboardHolder2.style.backgroundColor = 'white';
var blackRow = document.getElementsByClassName('black');
blackRow[0].style.top = '1px';
........
var parenttbl2 = document.getElementById('myrow2');
var newel2 = document.createElement('td');
var elementid2 = document.getElementsByTagName('td').length;
newel2.setAttribute('id', 'blackRow' + myrow2Id.toString());
newel2.style.textAlign = 'center';
if ([2,6,9,13,16,20].indexOf(myrow2Id) !== -1) {
parenttbl2.appendChild(newel2);
var el = docById('blackRow' + myrow2Id.toString());
el.style.background = 'transparent';
el.style.border = 'none';
el.style.zIndex = '10';
el.style.position = 'relative';
p--;
myrow2Id++;
continue;
}
this.layout[p].objId = 'blackRow' + myrow2Id.toString();
myrow2Id++;
newel2.style.position = 'relative';
newel2.style.zIndex = '200';
parenttbl2.appendChild(newel2);
HTML:
<html>
<head>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div id="floatingWindows"></div>
</body>
</html>
CSS:
#mkbKeyboardDiv {
position: relative;
left: 0px;
top: 0px;
border: 0 !important;
background: rgba(255, 255, 255, 0.85) !important;
width: 1020px;
}
I think I'm missing something, I just can't think of it. Is there any other way of putting space on each of the black div tags?
EDIT: I've added the HTML and CSS. The CSS is only for the keyboard's container. The white keys and black keys' CSS are all generated using Javascript

My hover popup is flickering and moving when it shouldn't

Trying to create a popup that will show when hovering over an element. However it flickers and moves around when I move my mouse inside the element. It should also stay open if the mouse moves over the popup.
Trying to do this without library cheats like jQuery. You don't learn if you use them.
If you hover your mouse over one of the tags below, that's exactly what I'm trying to create.
Think the error is somewhere in this code:
function showPopup(e) {
var popup = document.getElementById('popup');
if (popup.style.display == 'none') {
popup.style.display = 'block';
var bodyRect = document.body.getBoundingClientRect(),
elemRect = e.target.getBoundingClientRect(),
offsetX = elemRect.left - bodyRect.left,
offsetY = elemRect.bottom - bodyRect.top;
popup.style.left = offsetX + 'px';
popup.style.top = offsetY + 'px';
//console.log(e);
}
}
function hidePopup(/*e*/) {
setTimeout(function() {
var popup = document.getElementById('popup');
if (popup.style.display == 'block' && !window.inside_popup) {
popup.style.display = 'none';
window.inside_popup = false;
console.log('hide');
} else {
setTimeout(hidePopup, 50); // try a little later
}
}, 50); // Give the events ability to catch up and tell us the mouse is inside the popup
}
var targ = document.querySelector('ul li')
targ.addEventListener('mouseover', showPopup);
targ.addEventListener('mouseout', hidePopup);
Full javascript code with a real test element:
https://jsfiddle.net/g8wvae8o/
As #epascarello said, mouseleave and mouseenter are what you're looking for. There's no need for setTimeout here either. In addition, you're targeting every li on the page (is that intentional?) I recommend targeting a specific class of element to reduce flickering.
This is close, but you'll need to massage the positioning.
function createPopup() {
var container = document.createElement('div');
container.id = 'popup';
container.style.width = '500px';
container.style.height = '700px';
container.style.display = 'none';
container.style.position = 'absolute';
container.style.borderRadius = '2px';
container.style.border = '1px solid #242729';
container.style.backgroundColor = '#535a60';
container.style.color = '#e4e6e8';
container.style.zIndex = '9999999';
container.addEventListener('xmouseenter', function() {
window.inside_popup = true;
//console.log('window.inside_popup = true;');
});
container.addEventListener('xmouseleave', function() {
window.inside_popup = false;
//console.log('window.inside_popup = false;');
});
container.appendChild(document.createTextNode('This is a test'));
(document.body || document.documentElement).appendChild(container);
}
window.inside_popup = false;
createPopup();
function showPopup(e) {
var popup = document.getElementById('popup');
if (popup.style.display == 'none') {
popup.style.display = 'block';
}
}
function hidePopup(/*e*/) {
console.log('hiding')
popup.style.display = 'none';
window.inside_popup = false;
}
var bodyRect = document.body.getBoundingClientRect()
function updatePopup(e) {
var elemRect = e.target.getBoundingClientRect(),
offsetY = elemRect.bottom - bodyRect.top,
offsetX = elemRect.left - bodyRect.left;
popup.style.left = (e.clientX + offsetX) + 'px';
popup.style.top = offsetY + 'px';
}
var targ = document.querySelector('ul li')
targ.addEventListener('mouseenter', showPopup);
targ.addEventListener('mouseleave', hidePopup);
targ.addEventListener('mousemove', updatePopup)
Fiddle
Here's a pure CSS solution (I only use JS to create the popup elements)
window.addEventListener("load", function () {
var els = document.querySelectorAll("li");
els.forEach(el => {
var popup = document.createElement("div");
popup.innerHTML = el.getAttribute("popup");
popup.className = "popup";
el.appendChild(popup);
});
});
*[popup]:hover > .popup {
border: 1px solid #fff;
padding: 0.5em;
width: 400px;
height: auto
}
.popup {
overflow: hidden;
box-sizing: border-box;
background-color: black;
color: #ccc;
border-radius: 3px;
position: absolute;
height: 0px;
}
li {
margin: 2em 0
}
<ul>
<li popup="Some more info about this product">Move the mouse here</li>
<li popup="Some more info about the 2nd product">Some other product</li>
</ul>
The key to this is that the popup is a child of the element that is hovered, thus moving the mouse over the popup still counts as hovering the element.

How to clone the contents of a div into another div with JavaScript?

I want to clone the images of the div leftSide into the div rightSide. On each click on the body the images on the left div should be cloned into the right div. But I can't get the result with the code I'm doing. Is there any mistake in my code? I want to use JavaScript.
Here's my code:
var theLeftSide = document.getElementById("leftSide");
var width = 500; var height = 500;
top_position = 0; var left_position = 0,
var numberOfFaces = 5;
var theRightSide = document.getElementById("rightSide");
var leftSideImages = theLeftSide.cloneNode(true);
document.getElementById("rightSide").appendChild(leftSideImages);
for (var i = 0; i < 5; i++) {
createElement(i);
numberOfFaces += 5;
function createElement() {
var image = document.createElement('img');
image.src = "smile.png";
image.style.position = 'absolute';
image.style.top = top_position + "px";
image.style.left = left_position + "px";
theLeftSide.appendChild(image);
top_position = Math.random() * 500 ;
left_position = Math.random() * 500 ;
Here is a simple example that clones an HTMLElement in vanilla javascript:
additional information can be found in MDN
function CloneCtrl() {
'use strict';
var self = this;
self.source = document.querySelector('.source');
self.target = document.querySelector('.target');
self.cloneSource = function(event) {
var clone = self.source.cloneNode(true);
self.target.appendChild(clone);
}
document
.getElementById('cloneBtn')
.addEventListener('click', self.cloneSource)
;
}
document.addEventListener('DOMContentLoaded', CloneCtrl);
.source {
background: lightseagreen;
width: 100px;
height: 100px;
line-height: 100px;
overflow: hidden;
margin: 5px;
display: inline-block;
text-align: center;
color: #fff;
}
.target {
border: 1px solid lightcoral;
min-height: 110px;
}
<div><button id="cloneBtn">Clone Source</button></div>
<div class="source">SOURCE</div>
<hr>
<div class="target"></div>
With jQuery, you can do it kike that:
$('#div2').html($('#div1').html());
which is found from this question: Copy the content of a div into another div.
You don't actually provide many details, thus the best I can post, hope it helps!!
you could simply try this if you have second div on page.
document.getElementById("SecondDv").innerHTML = document.getElementById("FirstDv").innerHTML;
This will copy whatever is there in FirstDiv to Second. lmk if it works.

Absolute positioning for dynamically created elements

I am trying to overlay text onto a hyperlinked image which has been dynamically created using the document.createElement() function. However, even with an absolute position of left: 0px and top: 0px, the text keeps appearing below the image, and not at the top, left corner as it should:
//mainDiv is a container to hold all the hyperlinked images
for (i = 0; i < imgArray.length; i++)
{
img = document.createElement("img");
img.src = imgArray[i].src;
img.style.width = imgArray[i].wdth;
img.style.height = "auto";
imgLink = document.createElement("a");
imgLink.href = imgArray[i].url;
imgLink.appendChild(img);
imgLabel = document.createElement("p");
imgLabel.innerHTML = imgArray[i].desc;
imgLabel.style.position = "absolute";
imgLabel.style.top = "0px";
imgLabel.style.left = "0px";
imgContainer = document.createElement("div");
imgContainer.style.display = "inline";
imgContainer.style.position = "relative";
imgContainer.appendChild(imgLabel);
imgContainer.appendChild(imgLink);
mainDiv.appendChild(imgContainer);
}
The only problem is the positioning of the text div, imgLabel.
Here's a simplified example of the issue on jsFiddle: http://jsfiddle.net/mPL3q/1/
block & inline-block does not work: http://jsfiddle.net/MwjXV/
1st solution
// label
imgLabel.style.position = "absolute";
imgLabel.style.top = "0px";
imgLabel.style.left = "0px";
imgLabel.style.margin = '0px';
// container
imgContainer.style.position = "relative";
// tip: parent element of another element containing floated elements
// should have property overflow set to hidden
imgContainer.style.float = "left";
imgContainer.style.margin = "5px";
2nd solution
// label
imgLabel.style.position = "absolute";
imgLabel.style.top = "0px";
imgLabel.style.left = "0px";
imgLabel.style.margin = "0px";
// container
imgContainer.style.display = "inline-block";
imgContainer.style.position = "relative";
// you will have gaps between the containers even if the margin is set to 0
imgContainer.style.margin = "0px";
// if you don't want these gaps, set margin-left to -5px (but not to the first element)
if(i !== 0){
imgContainer.style.marginLeft = "-5px";
}
EDIT After analyzing your code...
// change <p> to <label>
imgLabel = document.createElement("label");
imgLabel.innerHTML = "Image " + i;
imgLabel.style.left = "0px";
// you don't need the next line ;)
//imgLabel.style.top = "0px";
imgLabel.style.color = "White";
imgLabel.style.position = "absolute";
1st jsFiddle | 2nd jsFiddle | 3rd jsFiddle
You can do this, add
img.style.zIndex="1";
and
imgLink.style.display = "block";
to their respective blocks
http://jsfiddle.net/mPL3q/8/
OR
if inline-block works for you then
imgContainer.style.display = "inline-block";
http://jsfiddle.net/mPL3q/7/

Categories