JQuery: Create image and div and then append image to div - javascript

I want to create an image object, then a div object, append the image to the div and finally append the result to a wrapper.
I did this:
var image = $(document.createElement('img'));
image.attr('src', url);
image.attr('id', 'preview_gallery_image_' + i);
image.addClass('admin-hotel-gallery-image');
var imageDiv = $(document.createElement('div'));
imageDiv.addClass('col-sm-3');
imageDiv.attr('id', 'preview_gallery_image_wrapper_' + i);
var imageNode = image.appendTo(imageDiv);
var finalElement = imageNode.appendTo("#gallery-wrapper");
To make it a bit clearer, the final result should look like this:
<div id="gallery-wrapper>
<div class="col-sm-3" id="preview-gallery-image-wrapper-1">
<img url="...">
</div>
</div>
What I get is only the image in the gallery wrapper, but the inner imageDiv around the image is missing:
<div id="gallery-wrapper>
<img url="...">
</div>
What am I doing wrong?

DEMO LINK
js code
var url = 'url';
var i =1 ;
var image = $('<img />', {
id:'preview_gallery_image_' + i,
class: 'admin-hotel-gallery-image' ,
src: url
});
var imageDiv = $('<div >',{
id: 'preview_gallery_image_wrapper_' + i
});
image.appendTo(imageDiv);
var finalElement = $('<div/>',{
id: 'gallery-wrapper'
});
imageDiv.appendTo(finalElement);
finalElement.appendTo('body');
result:
<div id="gallery-wrapper">
<div id="preview_gallery_image_wrapper_1">
<img src="url" class="admin-hotel-gallery-image" id="preview_gallery_image_1">
</div>
</div>

Related

Getting all image alt text values and appending into a list using vanilla JS

The following JS gives me a list of all the img alt text used on a webpage, showing either a name "name" or empty quotes "".
const altAtt = document.querySelectorAll("*[alt]");
const altText = Array.from(altAtt, (al, i) => al.getAttribute('alt'));
console.log(altText);
Question:
How do I get all the images with alt="" or alt="some name" and add them to a unordered list injected into the DOM?
I can create the structure document.createElement('ul'); etc. But no idea where to start adding the information into the list.
Somehow using li.innerHTML = altText[i];
Thanks in advance for any help.
I do have this using jQuery but really wish to write this in vanilla JS. The jQuery adds a Div element after each image which is what I want to eventually achieve with vanilla JavaScript :-)
$.each($("img"), function() {
var altText = $(this).attr('alt');
if (altText === "") {
$(this).after("<div class=\"no-alt-text\">This image is decoration</div>");
} else {
$(this).after("<div class=\"show-alt-text\">This image ALT text is: " + altText + "</div>");
$(function () {
$("div.show-alt-text:contains(\"undefined\")").each(function () {
$(this).removeClass("show-alt-text").html("<div class=\"empty-alt\">This image is missing an ALT attribute</div>");
$('div:empty').remove();
});
});
}
});
I think this is close to what you are looking for.
const imgElements = document.querySelectorAll("img");
const showAltText = document.createElement("div");
showAltText.classList.add("show-alt-text");
const noAltText = document.createElement("div");
noAltText.classList.add("no-alt-text");
noAltText.innerHTML = "This image is decoration";
for(let i = 0; i < imgElements.length; i++){
var altText = imgElements[i].alt;
if(altText === ""){
imgElements[i].after(noAltText.cloneNode(true));
}
else{
const element = showAltText.cloneNode(true);
element.innerHTML = "This image ALT text is: " + altText;
imgElements[i].after(element);
}
}
<!-- Alt Text -->
<img height="100" alt="test1" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
<!-- Alt Text -->
<img height="100" alt="test2" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
<!-- Empty Alt Text -->
<img height="100" alt="" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
<!-- No Alt Text -->
<img height="100" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />

Why jQuery cycle plugin doesn't work?

I write a function to append some HTML code to page like below:
function addGiftList(className, imgURL, Kind) {
var $li = $('<li class="' + className + '">');
var $img = $("<img>", { src: imgURL })
var $br = $("<br/>");
var $input = $('<input >', { type: 'radio', name: 'gift', kind: Kind });
var $label = $("<label>").text("Test");
$li.append($img);
$li.append($br);
$li.append($input);
$li.append($label);
return $li;
}
All this will append to a div with className cycle-slideshow then I call $('.cycle-slideshow').cycle();, but nothing happens. Does anyone know why?
Can I create HTML elements with javascript then call jQuery cycle plugin?
HTML
<button>append</button>
<div class="myslider composite-example" data-cycle-fx="scrollHorz" data-cycle-slides="> div" data-cycle-timeout="2000">
<div>
<img src="http://malsup.github.io/images/p1.jpg" width=100%>
<div class="cycle-overlay">first image</div>
</div>
<div>
<img src="http://malsup.github.io/images/p2.jpg" width=100%>
<div class="cycle-overlay">second image</div>
</div>
</div>
CSS
body {
width: 200px;
margin: auto;
}
img {
width: 200px;
}
JS
// first call cycle
$('.myslider').length > 0 && $('.myslider').cycle();
function addGiftList(className, imgURL, Kind) {
var $div = $('<div class="' + className + '">');
var $img = $("<img>", {
src: imgURL
})
var $input = $('<input >', {
type: 'radio',
name: 'gift',
kind: Kind
});
var $label = $("<label>").text("Test");
$div.append($img);
$div.append($input);
$div.append($label);
// dynamically adding slider: this is a plugin method see documentation
$('.myslider').cycle('add', $div);
return;
}
// dynamic add button for example
$('button').on('click', function() {
// add function for example
addGiftList('myclass cycle-slide', 'https://placeholdit.imgix.net/~text?txtsize=15&txt=image%20added&w=200&h=150&txttrack=0');
})
Please see this link of my codepen. I have solved your problem.
http://codepen.io/prashen/pen/PNPbRR

Inserting img in a div using another div's background image as a src in JS

there. How can I change my JS code in order to have only one image in my hidden_div? Here is my code.
Best regards.
<div onClick="show(this);" class="img" style="background-ima ge:url('css/images1/img/img1.jpg');background-size:100% 100%;")></div>
<div onClick="show(this);" class="img" style="background-image:url('css/images1/img/img2.jpg');background-size:100% 100%;")></div>
<div onClick="show(this);" class="img" style="background-image:url('css/images1/img/img3.jpg');background-size:100% 100%;")></div>
<div id="hidden_div"></div>
<script>
function show(element) {
var hidden = document.getElementById("hidden_div");
var imgElement = document.createElement("IMG");
imgElement.src=element.style.backgroundImage.replace('url(','').replace(')','');
hidden.appendChild(imgElement);
};
</script>
You make a small change in your script as follows
function show(element) {
var hidden = document.getElementById("hidden_div");
var imgURL = element.style.backgroundImage.replace('url(','').replace(')','');
var imgElement = "<img src='"+ imgURL +"' />
hidden.innerHTML = imgElement;
};
I don't understand very much what do you want, if you can explain to me, please.. But, I think inside of every 'div', in the 'style', there's a extra ) at the end.

jquery trouble - onclick for gallery

I am trying to use image gallery for my website that I found here. I want to add one more functionality to this gallery.. I want a large image to be linked and when clicked on it to open in new tab url that is defined in code.
I have included the full code here:
<script type="text/javascript">
$(document).ready(function()
{
/*Your ShineTime Welcome Image*/
var default_image = 'images/large/default.jpg';
var default_caption = 'Welcome to my portfolio';
/*Load The Default Image*/
loadPhoto(default_image, default_caption);
function loadPhoto($url, $caption)
{
/*Image pre-loader*/
showPreloader();
var img = new Image();
jQuery(img).load( function()
{
jQuery(img).hide();
hidePreloader();
}).attr({ "src": $url });
$('#largephoto').css('background-image','url("' + $url + '")');
$('#largephoto').data('caption', $caption);
}
/* When a thumbnail is clicked*/
$('.thumb_container').click(function()
{
var handler = $(this).find('.large_image');
var newsrc = handler.attr('src');
var newcaption = handler.attr('rel');
loadPhoto(newsrc, newcaption);
});
/*When the main photo is hovered over*/
$('#largephoto').hover(function()
{
var currentCaption = ($(this).data('caption'));
var largeCaption = $(this).find('#largecaption');
largeCaption.stop();
largeCaption.css('opacity','0.9');
largeCaption.find('.captionContent').html(currentCaption);
largeCaption.fadeIn()
largeCaption.find('.captionShine').stop();
largeCaption.find('.captionShine').css("background-position","-550px 0");
largeCaption.find('.captionShine').animate({backgroundPosition: '550px 0'},700);
Cufon.replace('.captionContent');
},
function()
{
var largeCaption = $(this).find('#largecaption');
largeCaption.find('.captionContent').html('');
largeCaption.fadeOut();
});
/* When a thumbnail is hovered over*/
$('.thumb_container').hover(function()
{
$(this).find(".large_thumb").stop().animate({marginLeft:-7, marginTop:-7},200);
$(this).find(".large_thumb_shine").stop();
$(this).find(".large_thumb_shine").css("background-position","-99px 0");
$(this).find(".large_thumb_shine").animate({backgroundPosition: '99px 0'},700);
}, function()
{
$(this).find(".large_thumb").stop().animate({marginLeft:0, marginTop:0},200);
});
function showPreloader()
{
$('#loader').css('background-image','url("images/interface/loader.gif")');
}
function hidePreloader()
{
$('#loader').css('background-image','url("")');
}
});
</script>
And I have 15 thumbnails/photos like this:
<div class="thumbnails">
<br><br><br>
<!-- start entry-->
<div class="thumbnailimage">
<div class="thumb_container">
<div class="large_thumb">
<img src="images/thumbnails/sample1.jpg" class="large_thumb_image" alt="thumb">
<img alt="" src="images/large/sample1.jpg" class="large_image" rel="Image Sample">
<div class="large_thumb_border"> </div>
<div class="large_thumb_shine"> </div>
</div>
</div>
</div>
<!-- end entry-->
</div>
Any help? Thanks.
This should work, all you have to do is add data-large attributes to each image and on hover it displays a tooltip with the large image inside.
http://jsfiddle.net/DSjLk/

Appending ascending images based on the id of parent div

Say I had the following three divs with unique ids on a page
<div id="product-id-001"></div>
<div id="product-id-002"></div>
<div id="product-id-003"></div>
What code would I need to add the following image elements based on the id of the div?
<div id="product-id-001">
<img src="images/product-id-001-1.jpg"></img>
<img src="images/product-id-001-2.jpg"></img>
<img src="images/product-id-001-3.jpg"></img>
</div>
<div id="product-id-002">
<img src="images/product-id-002-1.jpg"></img>
<img src="images/product-id-002-2.jpg"></img>
<img src="images/product-id-002-3.jpg"></img>
</div>
<div id="product-id-003">
<img src="images/product-id-003-1.jpg"></img>
<img src="images/product-id-003-2.jpg"></img>
<img src="images/product-id-003-3.jpg"></img>
</div>
Thanks for any tips.
$('div[id^=product]').each(function(index, elem) {
for(var i = 1; i < 4; i++) {
$('<img>', {
src: '/images/' + elem.id + i
}).appendTo(this);
}
});
Demo: http://www.jsfiddle.net/9S9Av/
(You need Firebug or another DOM inspector to see the result)
From the jQuery docs:
"The .append() method inserts the specified content as the last child of each element in the jQuery collection"
So:
$('#product-id-001").append('<img src="images/product-id-001-1.jpg"></img>');
etc...
// Select all elements with an id beginning with product-id:
var $productContainers = $('[id^=product-id]');
// Loop through the matched elements and append the images:
$productContainers.each(function () {
var $this = $(this),
productId = $this.attr('id'),
numImages = 3,
extension = '.jpg';
// Create and append the images based on the configuration above. Note that this
// assumes that each product have three valid images.
for (var i = 1; i <= numImages; i++)
{
var $image = $('<img alt="" />').attr('src', 'images/'+productId+'-'+i+extension);
$image.appendTo($this);
}
});

Categories

Resources