Change zIndex using javascript - javascript

It works on the premade divs but on the newly made one, it doesn't work. How do I fix that?
Here's the code on the event for changing the zIndex:
$(".widget").mousedown(function (event) {
var ws = document.getElementById("widget-workspace");
var list = ws.children, x=0;
for(x=0;x<ws.children.length;x++){
console.log(ws.children[x].id);
$("#"+ws.children[x].id).css("zIndex", 99);
}
$(this).css("zIndex", 100);
});
Now, here's the code for adding the div:
document.getElementById("widget-dialog-button").onclick = function () {
var ws = document.getElementById("widget-workspace");
var list = ws.children;
var x, w = document.getElementById("select-widget");
var widget = w.options[w.selectedIndex].value;
var c = document.getElementById("select-widget-color");
var color = c.options[c.selectedIndex].value;
var left = 0, top = 25, docWidth = ws.offsetWidth, check;
for(x=0; x < list.length; x++){
docWidth -= 325;
left += 325;
if(docWidth < 325){
check = false;
docWidth = ws.offsetWidth;
left = 0;
top += 210;
}else{
check = true;
}
}
x-=2;
var iDiv = document.createElement('div');
iDiv.id = 'widget_'+x;
iDiv.className = 'widget';
iDiv.style.backgroundColor = color;
iDiv.style.left = left;
iDiv.style.top = top;
ws.appendChild(iDiv);
$(function() {
$( ".widget" ).draggable();
});
};
If you guys need anything else, feel free to ask.

The answer is quite simple :
"It works on the premade divs but on the newly made one, it doesn't work. How do I fix that?"
It's normal :
$(".widget").mousedown(...);
// should be read as (except that a new var is not created)
var $currentlyExistingWidgets = $(".widget");
$currentlyExistingWidgets.mousedown(...);
To each element of class widget currently existing, you bind an event.
If you want to bind events to elements not existing... You have to reconider your way of thinking and then bind an event listener to a container always existing, with an event delegation mechanism and proper filtering.
For example the following code should catch the event for all .widget, created before or after :
// http://api.jquery.com/on/
$('body').on('mousedown', '.widget', function() { ... });
If you want to search and learn, the key concepts are event bubbling and event delegation.

The way you're attaching the mousedown listener means that only the element that exist at that point will be listened to. Use the on method:
// May want to use something other than body
$('body').on('mousedown', '.widget', function() {
console.log('go');
});
Docs

Related

Javascript addEventListener not working properly

So i'm having trouble with the event so, normally i try to create an event if we have more than 1 image in the array so i can mouseenter and display another one but currently i don't know why but when we mouseenter the preview (image) it giving the latest result from the array while we still inside the loop ?
var product_type = "";
for(let i = 0; i < this.products_list.length; i++){
var row = this.products_list[i], self = this;
if(row.product_type != product_type){
product_type = row.product_type;
var sub_title = document.createElement("h2"),
separator = document.createElement("hr"),
display_list = document.createElement("ul");
sub_title.id = product_type;
sub_title.innerHTML = localeString.get(product_type);
display_list.id = product_type+"-list";
this.catalog.appendChild(sub_title);
this.catalog.appendChild(separator);
this.catalog.appendChild(display_list);
}
var product = document.createElement("li"),
preview = document.createElement("img"),
container = document.createElement("div");
var array_images = row.product_images.split(",");
preview.src = this.assets+product_type+"/"+array_images[0]+".jpg";
preview.alt = product_type+"#"+row.product_id;
container.appendChild(preview);
product.appendChild(container);
preview.addEventListener("mouseenter", event => {
console.log(array_images);
//here, giving the latest element from the array and not the current selected.
});
display_list.appendChild(product);
}
If your are trying to opt for mouseover event then you should use mouseover in the place of click event. Currently its not working because the event which you called is a click event.

How to get the img id for dynamically building IMG tags based on click like Share or Like or Comment

Good Evening Everyone.
Background: I am getting list of images from a Mongo Database and then I am calling ajax once to load those data in to particular div.
Here I am building those img tags dynamically and then appending it to a div.
Now I am trying to get the img id based on user operation, lets say clicks on 'share button' for a particular img, then I have to get the image id, and then have to look search the DB with that image id.
My code after the ajax call is:
function showImages(imageList) {
for ( var i = 0, len = imageList.length; i < len; i++) {
var elem = document.createElement("img");
elem.src = 'getImg/' + imageList[i][0] + '/' + imageList[i][1];
elem.id = imageList[i][2];
alert(elem.id);
elem.height = '100';
elem.width = '100';
elem.alt = 'SPF HYD';
/* $("a[id=shareImage]").click(function(){
var qwerty = $("img", $(this).parent()).attr("id");
alert('image id is after anchor by click...'+qwerty);
}); */
var image = document.getElementById("imageLoad");
image.appendChild(elem);
}
}
Could any one help me to get the image id onclick or any button trigger?
I threw a quick demo together to demonstrate what I meant. It's made possible using jQuery event Delagation
function showImages(imageList) {
for ( var i = 0, len = imageList.length; i < len; i++) {
var elem = document.createElement("img");
elem.src = 'getImg/' + imageList[i][0] + '/' + imageList[i][1];
elem.id = imageList[i][2];
console.log(elem.id);
elem.height = '100';
elem.width = '100';
elem.alt = 'SPF HYD';
var image = document.getElementById("imageLoad");
image.appendChild(elem);
}
}
//The event handler is registered on the document object - the second argument here is the delegate, <img>
$(document).on("click", "img", function(e) {
alert($(this).attr("id"));
});
var imageList = [[0, 1, 2], [3, 4, 5]]; //These values are merely for testing
showImages(imageList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imageLoad"></div>
Using Event Delegation is necessary here because your img tags are being dynamically generated, plus it's a lot cleaner to register one event handler for all img tags, rather than an event handler for each
Hope this helps
Use addEventListener function to add an Event Listener to your dynamically created element.
var div = document.getElementById("div");
var imgShare = document.createElement("img");
imgShare.src = "http://icons.iconarchive.com/icons/graphicloads/100-flat-2/128/share-2-icon.png";
imgShare.id = "post002";
imgShare.addEventListener("click", share);
div.appendChild(imgShare);
var imgLike = document.createElement("img");
imgLike.src = "http://www.brandsoftheworld.com/sites/default/files/styles/logo-thumbnail/public/102011/like_icon.png?itok=nkurUMlZ";
imgLike.id = "post001";
imgLike.addEventListener("click", like);
div.appendChild(imgLike);
function share(e){
alert("Share id:" + e.currentTarget.id);
}
function like(e){
alert("like id:" + e.currentTarget.id);
}
<div id="div"></div>
JSFiddle Link...

dynamically added button on click not working

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

Javascript Create Clickable Text

EDIT 2 - I decided to create a simple example with jsfiddle.
http://jsfiddle.net/VqA9g/61/
As you can see, I am trying to reference the new div.
EDIT - d/t negative votes and unclear question
I have a linked-list like so:
var struct_list = function () {
this.id = 0;
this.name = 0;
this._head = null;
};
struct_list.prototype = {
// .. adding code , delete code ...
list_contents: function () {
var current = this._head;
while ( current != null ) {
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "white";
div.style.color = "black";
div.style.top = "0px";
div.style.left = "0px";
div.style.margin = "400px 1000px auto";
div.style.cursor = "pointer";
div.innerHTML = current.name;
div.onclick = function ( v ) { var d = document.getElementById('div'); alert(d)};
document.body.appendChild(div);
current = current.next;
}
return null;
},};
I want to be able to display this linked list, and each item displayed be able to interact with an "onclick".
Example:
struct_list.add ( 0 , "Zero" );
struct_list.add ( 1 , "One" );
struct_list.list_contents();
_________________________________________________________________________
| |
| <clickable> "Zero" that does a function(id) that passes over its ID(0) |
|________________________________________________________________________|
| |
| <clickable> "One" <same as above> |
|________________________________________________________________________|
Sorry if I was unclear. Will reedit if still unclear. My apologies.
I have a linked-list struct that I hold data in (it changes data frequently) and I have a setInterval to refresh it. My question is how can I list the struct's contents while still being able to click the exposed content, I have it set up right now that each content in the linked-list contains an id. Also , how can I make sure that overflow is automatic for the y axis? I am guessing I have to place it into a div that has that enabled.
But my real question is how to expose the linked-lists elements while also being able to interact with them via an onclick.
I also do not want to use anything other than pure javascript.
Example (in my mind) would maybe be something like:
<div id="PopUp">
<script>
setInterval(function() {
if ( struct_qued_list ) {
struct_qued_list = false;
main.struct_list.list_contents(); // the linked list
}
}, 100);
</script>
</div>
list_contents: function () {
var current = this._head;
while ( current != null ) {
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "white";
div.style.color = "black";
div.style.top = "0px";
div.style.left = "0px";
div.style.margin = "400px 1000px auto";
div.style.cursor = "pointer";
div.innerHTML = current.name;
div.onclick = function ( v ) { var d = document.getElementById('div'); alert(d)};
document.body.appendChild(div);
current = current.next;
}
return null;
},
Any help or logical way to do this would be appreciated.
This is mainly a scope problem, in your Edit 2 fiddle, the alert gives undefined because your i got the value 2 in order to leave the loop.
Here is a possible solution : Live demo (jsfiddle)
!function(){
var index = i; // Make it independant of i
div.onclick = function () { alert(list[index]); };
}();
You could also use attributes to store any value, and using this in the function to retrieve it.
Or export the whole process to another function to obtain something like this :
for ( var i = 0; i < 2 ; i++ ) {
doSomething(i);
}
When you add new content to the DOM JavaScript sometimes has a hard time picking that up. You may need to use a DOM mutation event (like DOMNodeInserted) to add the event listeners to your text nodes.
document.addEventListener('DOMNodeInserted', function(){
document.getElementById('thing').addEventListener('click', function(){
alert('yey!');
});
});
you may need to name your functions so you can remove them as well, if nodes are going to be inserted without removing all the old ones. Yes this is pure javascript.
EDIT: for your overflow issue, you could assign a class to each node as you insert it and style the class via CSS
.classname {
overflow: auto;
}

innerHTML and event delegation

I have a containing div that has multiple divs within which is updated every 25ms using innerHTML (for performance reasons). I have tried using event delegation to capture events but nothing I seem to do captures the click event. I think this may be due to the speed that the contents are getting updated. Any ideas would be very welcome.
My code:
$(document).ready(function () {
var canvas = $('#gCanvas')[0];
$(document.body).delegate('a', 'click', function (e) {
console.log(e.target);
});
var sprites = [];
for (var i = 0; i < 100; i++) {
sprites[i] = {x: i+10, y: i+10};
}
var doIt = function () {
var s = '';
for(var i = 0; i < sprites.length; i++) {
var spr = sprites[i];
spr.x++;
spr.y++;
s+= '<a id="s'+i+'" class="s" style="left:'+sprites[i].x+';top:'+sprites[i].y+'"></a>';
}
canvas.innerHTML = s;
};
//doIt();
setInterval(doIt, 50);
});
it easy if you use jquery. there is a .live function, but i am not sure if it quick enough. alternatively you could try to check jquery source to find the .live() code and find the solution
UPDATE
if you are trying to make a game then you can try to use svg for good browsers and vml for bad ones.

Categories

Resources