Javascript clone/append either affects the wrong image or all images - javascript

I have a pretty basic function that gets a result set of images based on search input
function appendSomeItems(url, id, name, style) {
return '<div><div class="md-card md-card-hover"><div class="gallery_grid_item md-card-content getImage"> <img class ="uk-align-center imageClick"></a><div class="gallery_grid_image_caption"> <span class="gallery_image_title uk-text-truncate">' + name + '</span> <span>' + style + '</span> </div></div></div></div>';
}
This works perfectly fine, and it is called in another function that basically gets up to 10 images from the result set and appends them in a div.
I have another function where I'm clicking one image and I want THAT specific image to clone and append to another div. The problem is, using class imageClick it clones and appends all images to the new div. If I change imageClick to an ID then it only clones/appends the first in the set.
How can I alter this to only clone and append the clicked image?
$(document).on('click', '.imageClick', function handleImage() {
console.log('good');
var img = $(".getImage").children("img").clone();
$("#holdImage").append(img);
});

Try .closest() on $(this) to target only the currently clicked image:
var img = $(this).closets(".getImage").children("img").clone();
Your current HTML suggest that you have only one image element which you are cloning. In this case finding children is meaningless. Simply cloning $(this) is enough:
var img = $(this).clone();

Use closest:
var img = $(this).closest(".getImage").children("img").clone(true);

Related

Add element to a div with javascript

I want to add an element (child, div) to a mother-div, that already has one or more children. I made a script for this action but when I execute the script I am not able to manipulate style attributes afterwards. So I assume I did something wrong in my creation-script. I also added a console message (end of the script) and that also indicates there are no style attributes filled in at the new div. So, please could someone indicate what the reason is...
As I am quite new to javascript I assume the reason is quite simple. But although I checked many other questions and solutions, I do not get the proper solution for my issue. I think it should be in appendChild or insertBefore.
function preparevideo(videonaam, titel) {
// add a div to the video-div
const nieuwetitel = document.createElement("div");
// give the new div an id so it will be unique
nieuwetitel.id = videonaam + '-id';
// give the div a class for the markup
nieuwetitel.className = 'page-roel-video-titel';
// create the text in the div
const textnode = document.createTextNode(titel);
// add the textnode to the div
nieuwetitel.appendChild(textnode);
// find the element where the new div should be added to
let videomodule = document.getElementById(videonaam);
// and finally add the new div to the video-div, as the first child
videomodule.insertBefore(nieuwetitel, videomodule.children[0]);
console.log('-------after adding div------');
console.log('-------complete style of titleblock------');
console.log(document.getElementById(videonaam + '-id').style);
console.log('prepare video afgerond');
}
preparevideo("naam1","Eerste video");
<div id="naam1"></div>
As you didn't set any style attribute before console.log that's why you didn't get any result. After implementing some style, you can log the the style. Then you will see the difference.
Here I added some style before the console.log
function preparevideo(videonaam, titel) {
// add a div to the video-div
const nieuwetitel = document.createElement("div");
// give the new div an id so it will be unique
nieuwetitel.id = videonaam + '-id';
// give the div a class for the markup
nieuwetitel.className = 'page-roel-video-titel';
// create the text in the div
const textnode = document.createTextNode(titel);
// add the textnode to the div
nieuwetitel.appendChild(textnode);
// find the element where the new div should be added to
let videomodule = document.getElementById(videonaam);
// and finally add the new div to the video-div, as the first child
videomodule.insertBefore(nieuwetitel, videomodule.children[0]);
// Applying style
document.getElementById(videonaam + '-id').style.backgroundColor = 'red';
document.getElementById(videonaam + '-id').style.color = 'white'
console.log('-------after adding div------');
console.log('-------complete style of titleblock------');
console.log(document.getElementById(videonaam + '-id').style);
console.log('prepare video afgerond');
}
preparevideo("naam1","Eerste video");
<div id="naam1"></div>
You already gave it a class, you can target it in your css and added the needed styles
The problem is that there is no unique id value for nieuwetitel element generated. When you use getElementById() method you get only first element from DOM.

Sending a Static Value as a Parameter in an Event Listener

Using Javascript (and jQuery), I have an array of several objects. For each object in that array, I'm adding a small, clickable image to a div. Clicking each small image will change the path of a large image, thus showing a new picture.
Here's what I've got:
for (s = 0; s < splash.length; s += 1)
{
// add a new dot to this row
$(".splash_dots").append ("<div class = 'dot' id = 'dot" + s + "'><img src = 'images/dot2.png'></div>");
var id = 'dot' + s;
// add a click handler
document.getElementById (id).addEventListener ("click", function () {change_splash (s)});
}
//////////////////////////////////////////////////
function change_splash (s)
{
// load a new image for the large photo
$(".splash").attr ("src", splash[s].screenshot_link);
}
This almost works. The problem is that when change_splash() is called, I'm expecting the value of s to be what it was when the loop added the handler. For example, clicking the first dot will call change_splash(0). However, it's actually sending what s is when the click happens (after the loops ends, which is always array.length).
I have a temporary solution, but I don't like it::
if (s === 0) document.getElementById (id).addEventListener ("click", function () {change_splash (0)});
if (s === 1) document.getElementById (id).addEventListener ("click", function () {change_splash (1)});
This just seems really inefficient.
I'm basically just trying to create a sliding splash advertisement, like what you'd see on almost any retail homepage, so I know it's possible. Any ideas are appreciated.
Try with this
for (var s in splash){
// create the points, stores the id in the data-id attribute
$(".splash_dots").append ("<div class ='dot' data-id='" + s + "'><img src='images/dot2.png'></div>");
}
// click listener
$("body").on("click",".dot",function(){
// retrieve the id from the data-id attribute
var s = $(this).attr("data-id");
$(".splash").attr ("src", splash[s].screenshot_link);
});
See it in action in JSFiddle demo
you'll need a closure:
(function(id,s){
document.getElementById(id)
.addEventListener("click", function(){change_splash (s)});}(id,s));

Remove dynamically added checkboxes and corresponding images

I have a button which opens a file selector window. When the user selects a file, the script uploads that image to a div with a checkbox.
This is the part of the script that removes the checkbox and image, but it is currently removing the parent element as well.
$("#imageForm").on('click', 'input[value="Delete"]', function () {
$('#iso_preview').has('input:checkbox:checked').remove()
});
How can I remove all checked checkboxes and their corresponding images when the delete button is clicked?
jsFiddle
You need to alter your insert fileUpload() function so that the image is contained within the inner wrapper. Change the following lines
if (imageType.test(file.type)) {
fileTemp = document.createElement("img");
$("#iso_preview").append("<div class='ct'><input value='remove'type='checkbox'/></div>");
fileTemp.classList.add("preview_image");
} else{
fileTemp = document.createElement('div');
fileTemp.classList.add('div');
}
fileTemp.file = file;
$('#'+preview).append(fileTemp);
To this...
var container = $("<div class='ct'><input value='remove'type='checkbox'/></div>");
if (imageType.test(file.type)) {
fileTemp = document.createElement("img");
fileTemp.classList.add("preview_image");
} else{
fileTemp = document.createElement('div');
fileTemp.classList.add('div');
}
fileTemp.file = file;
container.append(fileTemp);
$("#iso_preview").append(container);
Then you need to make a slight modification in this line
$('#iso_preview').has('input:checkbox:checked').remove();
To select #iso_preview div instead of #iso_preview
$('#iso_preview div').has('input:checkbox:checked').remove();
This will remove any div elements containing a checked checkbox that is contained within #iso_preview
(Demo)

Declare a base variable for methods in JQuery

The answer is below
I'm just starting to get into JQuery but I don't if I'm just slow understanding or stupid....
Let's say I wanna make a function where all my li objects... when you do a mouseover it gets the class name of the corresponding li element, and declaring a variable inside of it to keep that name, well my question is... how can I edit it with .css method and make a simple image swap ( image which is find through the class)
$("li")
.mouseover(function() {
var $myClass = $(this).attr("class");
var src = $($myClass).find('img').attr("src").match(/[^\.]+/) + "_over.png";
$("img"+ myClass).attr("src", src);
$($myClass).css("background-color", "#fff");
})
I don't know why it's not working, i'm guessing it's because my variable only display the name and not the actual name to edit it with jquery, I mean I don't know if it's adding the "." or "#" depending if it's a div or class for the code syntax, but I have no idea how to add that "." to the variable... or maybe it's because of my nested rules with my li objects, I mean to specifically refer to my li objects is:
#nav li
And yeah I know I'm telling solutions but I can't make em work :S
Anyone can help me?
**I did it haha! (What I was trying to do is change an <image> (with generic name) and class properties inside of a specific li object, knowing that li through their class when user triggers mouse over)
I'm just adding the code if anyone find this question helpful**.
$("li")
.mouseover(function() {
var $myClass = $(this).attr("class");
$myClass = "." + $myClass + " a";
var src = $($myClass).find('img').attr("src").match(/[^\.]+/) + "_over.png";
$myImg = $myClass + " img";
$($myImg).attr("src", src);
$($myClass).css("color", "#fff");
})
.mouseout(function() {
var $myClass = $(this).attr("class")
$myClass = "." + $myClass + " a";
var src = $($myClass).find('img').attr("src").replace("_over", "");
$myImg = $myClass + " img";
$($myImg).attr("src", src);
$($myClass).css("color", "#E3C922");
});
You can just do this in css:
.yourClass{
background: url(/path/image.jpg);
}
.yourClass:hover{
background: url(/path/image_over.jpg);
}
unless you have individual images for each li. Then you may want to clarify your needs so I can update this to a more useful answer.
just in case...
$("li")
.mouseover(function() {
var src = $(this).find('img').attr("src").match(/[^\.]+/) + "_over.png";
$(this).find("img").attr("src", src);
$(this).css("background-color", "#fff");
})
there's no reason to declare the myCLass var when you're within scope of that object alone. So you add the over state, then change the src of the img found and the li's background color.
An easy way to do this is to have one css class for the "li" element when it is not being hovered over and then another css class for when it is being hovered over with the background image set to whatever you want.
Then, in your jQuery you would use the removeClass() function and the addClass() function. The addClass() function would add the class with your hovered image.
Are you looking to change the class on mouse over?
$(li).mouseover(function{$(this).addClass("whatever");});
$(li).mouseout(function{$(this).removeClass("whatever");});
you can also use toggleClass() method
You can use the $varname method for variable declaration var keyword

I generated html code (lots of divs) with javascript. Now I want to find the generated divs with GetElementById

GetElementById works if I manually added a div id="something" inside the body and use window.onload = init method in the script to get it. Works great.
But if I used a for loop to generate divs where id's is 1,2,3 and so on. I can't get it. Is there a way to get to those generated divs?
This is what generates the html code (just to be clear what I mean):
for(i=0; i<randomizeColoursList.length; i++)
{
document.getElementById("renderColors").innerHTML +=
'<div class=\"box\"><div class=\"' + i + '\"><font color=\"'
+ randomizeColoursList[i] + '\">'
+ "" + '<img src=\"dist/card_bg.gif\"></div></div>';
}
Generates one of these:
<div class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div>
Div with class 8 is the id I want to get for example. But is says it's null.
Thanks.
The id is null because you haven't specified it in your markup creation. Looks like you're assigning the id value to class instead.
Generate something more like this:
<div id="div1" class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div>
Also, you don't need to use font tags, nor should you use them. Just add the styling to the div.
<div id="div1" class="8" style="color:#3be6c4;"><img src="dist/card_bg.gif"></div>
The way you're going about this is a little backwards. If you write your code like I have below, then you don't need to give the divs IDs, you end up with an array full of references to them anyway.
var i, div, img;
var createdDivs = [];
for(i=0; i<randomizeColoursList.length; i++)
{
div = document.createElement('div');
img = document.createElement('img');
div.className = "box";
div.style.backgroundColor = randomizeColoursList[i];
div.style.color = randomizeColoursList[i];
img.src = "dist/card_bg.gif"
div.appendChild(img);
document.getElementById("renderColours").appendChild(div);
createdDivs.push(div);
}
Live link: http://jsfiddle.net/7HjLL/

Categories

Resources