I'm building a function in my own image browser that creates and displays a delete button when the user hovers the cursor over a certain image's div and hides the button when the user hover the mouse out of the div.
this is the code:
function displayImages() {
//run through array of images
for (a = 0; a < images.length; a++) {
var container = document.createElement('div');
container.id = 'container'+images[a];
container.style.width = 120;
container.style.backgroundColor = '#e9e9e9';
container.style.height = 140;
container.style.margin = 5;
container.style.display = 'inline-block';
container.style.float = 'left';
var imageID = images[a];
container.onmouseover = function() {imageRollover(this)};
container.onmouseout = function() {imageMouseOut(this)};
}
}
function imageRollover(image) {
var trashcan = document.createElement('BUTTON');
trashcan.id = 'trash'+image.id;
trashcan.className = 'deleteButton';
trashcan.onclick = function() {deleteImage(image.id);};
document.getElementById(image.id).appendChild(trashcan);
}
function imageMouseOut(image) {
document.getElementById(image.id).removeChild(document.getElementById('trash'+image.id));
}
function deleteImage(image) {
alert(image);
}
My problem is, that when I click trashcan, it calls nothing. I already tried to add the onlick event normally:
trashcan.onclick = deleteImage(image.id);
But then, for some reason, is calls the function when I hover my mouse over the container.
How do I make sure that on click events for dynamically added rollover buttons work?
The function can de viewed on: http://www.imaginedigital.nl/CMS/Editor/ImagePicker.html or http://jsfiddle.net/f239ymos/
Any help would be highly appreciated.
You are forcing me to guess here(not giving a fiddle), and create a scenario of my own but from what I understand, you want a button to appear no hover, and when pressed to delete the image so here its a working fiddle
hover functionality
$((document.body).on('mouseenter', '.test', function(){
console.log('here');
$(this).children('.test .x_butt').show();
});
$(document.body).on('mouseleave', '.test', function(){
$('.test .x_butt').hide();
});
remove functionality
$(document.body).on('click', '.x_butt', function(){
$(this).parent().remove();
});
P.S. as for your dynamically added divs issue, the $(selector1).on('click','selector2', function() {...}); deals with it, as long as selector1 is not added dynamically. (selector2 would be the div you want the function to be on) demo with dynamically added elements ( click clone )
First change
window.onload = loadImages(); to window.onload = loadImages;
Then since you pass an object you can change
function imageMouseOut(image) {
document.getElementById(image.id).removeChild(document.getElementById('trash'+image.id));
}
to
function imageMouseOut(image) {
image.removeChild(image.childNodes[0]);
}
However why not just hide and show the trashcan? Much cleaner
Related
I created a simple new tab page similar to web browsers, but when I create a new tab and press the x icon to triger closetab() it closes all the tabs and does not delete them in order one by one. How do i make each of appended items unique?
JS:
function addTab() {
var img = document.createElement("img");
img.src = "resources/img/delete-icon.svg";
img.className = 'deleteicon';
img.id = "deletetab";
img.onclick = closeTab;
var ulLocation = document.getElementsByClassName('abc')[0];
var whereTab = document.getElementById('listid');
var addTab = document.createElement('li');
addTab.className = 'first-tab';
addTab.id = "listid";
addTab.className = 'active';
addTab.innerHTML = "mozilla-firefox/newtab";
addTab.appendChild(img2);
ulLocation.appendChild(addTab);
addTab.appendChild(img);
}
function closeTab() {
var whereTab = document.getElementById('listid');
if (whereTab.style.display == 'block') {
whereTab.style.display = 'none';
} else {
whereTab.style.display = "none";
}
}
You have at least 2 options. One is to target the active tab and close it when the X is clicked. This is assuming you only have one active tab at a time (denoted by an active class for example).
function closeTab(event) {
document.querySelector('li.tab.active').remove();
}
Another option is to reference the tab relative to the close icon, which you can reference in the event argument of your click listener. Since you're adding these dynamically, you can just remove them with the delete click rather than hide. Something like:
function closeTab(event) {
event.target.closest('li.tab').remove();
}
In these examples, you have set a className for your tab containers to be tab
this might be a very stupid question. I want to access different divs and interact with one another without using buttons functions, so I am trying to turn a normal div into a function when it hovers and then when out it does another animation and when clicked it should do something else.
https://jsfiddle.net/Lshp4ofw/67/
var BaseGraph = document.getElementById("BaseGraphic");
var BaseGraph = BaseGraphAct;
var BaseGraphAct = function(){
if(BaseGraph){
BaseGraph.addEventListener("mouseover", function(event) {
event.InteraBase = document.getElementById("InteractionBase");
InteraBase.classList.remove("dead");
});}
}
Here is example how you can change state of div with class 'dead' from another div:
var BaseGraph = document.getElementById("BaseGraphic");
var IB = document.getElementById("InteractionBase");
BaseGraph.addEventListener("mouseover", function(event) {
IB.classList.remove('dead');
});
BaseGraph.addEventListener("mouseout", function(event) {
IB.classList.add('dead');
});
I have some code for the function that runs when a button is clicked in my site:
function shadow() {
document.getElementById("overlay").style.visibility="visible";
document.getElementById("dim").style.visibility="visible";
document.getElementById("dim").onclick="document.getElementById('dim','overlay').style.visibility='hidden'";
}
With overlay being the overlay div that I want to be re-hide-able, and dim being the lower z-index dimmer over the entire page when the function runs.
The third line is my attempt at making it so that when an area outside of the overlay is clicked, the dim and overlay go away - help on that would be great!
The onclick property expects a function reference, not a string. In addition, the getElementById method only accepts a single id parameter, which means that only the first element id that you passed to it would be selected.
Based on the code you provided, it looks like you want something like this (live example):
function shadow() {
var overlay = document.getElementById('overlay');
var dim = document.getElementById('dim');
overlay.style.visibility = 'visible';
dim.style.visibility = 'visible';
dim.onclick = function() {
overlay.style.visibility = 'hidden';
dim.style.visibility = 'hidden';
};
}
Alternatively, you could also add a click event listener to document and then determine whether event.target is the #overlay element.
For instance, the following would work (live example):
document.addEventListener('click', function (event) {
var overlay = document.getElementById('overlay');
var dim = document.getElementById('dim');
if (event.target !== overlay && !event.target.closest('#overlay')) {
overlay.style.visibility = 'hidden';
dim.style.visibility = 'hidden';
}
});
I want to load all images before displaying them in a slideshow. I have been searching a lot but nothing seems to work. This is what i have so far and it doesn't work. I am loading images from the <a> tag from another div.
$('.slideshow').load(function(){
if (loaded<length){
first = $(settings.thumb).eq(loaded).find('a').attr("href");
$('<img src="'+first1+'"/>').appendTo('.slideshow');
}
else{ $('.slideshow').show(); }
loaded++;
});
Add an event listener to each image to respond to when the browser has finished loading the image, then append it to your slideshow.
var $images = $("#div_containing_images img");
var numImages = $images.length;
var numLoaded = 0;
var $slideshow = $(".slideshow");
$images.each(function() {
var $thisImg = $(this);
$thisImg.on("load", function() {
$thisImg.detach().appendTo($slideshow);
numLoaded++;
if (numLoaded == numImages) {
$slideshow.show();
}
});
});
It's a good idea to also listen for the error event as well, in case the image fails to load. That way you can increase numLoaded to account for broken image. Otherwise, your slideshow will never be shown in the event the image is broken.
Also note, that by calling detach() followed by appendTo() I am am moving the image in the DOM. If instead, you want to copy the image, use clone() instead of detach().
* EDIT TO MODIFY USER'S EXACT USE CASE *
var $images = $("li.one_photo a");
var numImages = $images.length;
var numLoaded = 0;
$images.each(function() {
$('<img />',
{ src: $(this).attr("href") })
.appendTo('.slideshow')
.on("load error", function() {
numLoaded++;
if(numLoaded == numImages) {
$('.slideshow').show();
}
});
});
* EDIT #2 *
Just realized you were putting everything in the $(".slideshow").load() function. Since $(".slideshow") represents a DIV, it will never raise a load event, and the corresponding function will never execute. Edited above accordingly.
It works but there's a pesky bug I can't understand how to fix (i'm a beginner).
What happens is there are 3 image buttons (only showing code for 1 here) and when i hover over them, they change image, and revert when i take mouse off. This is the html.
When I click any of the 3 image buttons (javascript), it changes its own image, and sets the other 2 image buttons to the normal image.
After this point (clicking the image) the hovering html code doesn't work anymore.
function changeImage3() {
document.getElementById('MageBTN').src = 'images/Character/NotSelected_Mage.png';
document.getElementById('WarriorBTN').src = 'images/Character/NotSelected_Warrior.png';
}
<a href="#" onclick="changeImage3()"><img id="RogueBTN" src="images/Character/NotSelected_Rogue.png" alt="image"
onclick="this.src='images/Character/Selected_Rogue.png';
this.onmouseover = false; this.onmouseout = false;"
onmouseover="this.src='images/Character/Selected_Rogue.png';"
onmouseout="this.src='images/Character/NotSelected_Rogue.png';">
</a>
just suggestion.. Use simple css property..
#yourID a:hover{
//your image which want to show on hover
}
If I have understand correctly you want to lock the selected state of a button on click and unlock/reset to not-selected when another button is clicked. Therefore you have to store the state of the buttons so I suggest to move all functionality to a script. Since you have all images well ordered it's enough to change Sel/NotSel in the url.
window.onload = function() { // ensures that all elements are there
var buttons = {
RougeBTN: document.getElementById("RougeBTN"),
VertBTN: document.getElementById("VertBTN"),
BleuBTN: document.getElementById("BleuBTN")
},
locked;
function clicked() {
for (var btn in buttons) { // iterate over the buttons
var b = buttons[btn];
// if this button was clicked save the state
if (btn == b.id) locked = btn;
else {
b.src = b.src.replace('/Sel', '/NotSel');
}
}
}
function mover() { // works only when button is not locked
if (locked != this.id) this.src = this.src.replace('/NotSel', '/Sel');
}
function mout() { // works only when button is not locked
if (locked != this.id) this.src = this.src.replace('/Sel', '/NotSel');
}
for (var btn in buttons) { // now set the functions to all buttons
var b = buttons[btn];
b.onclick = clicked; b.onmouseover = mover; b.onmouseout = mout;
}
}
In html all buttons look like this:
<img id="RougeBTN" src="images/Character/NotSelected_Rouge.png" alt="image">