How to make a thumbnail created by a function clickable in html? - javascript

I am trying to make clickable thumbnails in my html code but I cannot figure out how to do it. I know <a href = ""> won't work. How can I make each thumbnail clickable so that it directs to another page?
Here are the functions I used to get data from the database and to create the thumbnail
`
<script>
$(function(){
$.ajax({
url: '/getMovies',
type: 'GET',
success:function(response) {
console.log(response);
var data = JSON.parse(response);
var itemsPerRow = 0;
var div = $('<div>').attr('class','row');
for(var i=0;i<data.length;i++){
console.log(data[i].Title);
if(itemsPerRow<3){
console.log(i);
if(i==data.length-1){
div.append(CreateThumb(data[i].Id,data[i].Name,data[i].Type,data[i].Copies));
$('.well').append(div);
}
else{
div.append(CreateThumb(data[i].Id,data[i].Name,data[i].Type,data[i].Copies));
itemsPerRow++;
}
}
else{
$('.well').append(div);
div = $('<div>').attr('class','row');
div.append(CreateThumb(data[i].Id,data[i].Name,data[i].Type,data[i].Copies));
if(i==data.length-1){
$('.well').append(div);
}
itemsPerRow = 1;
}
}
},
error:function(error){
console.log(error);
}
});
});
})
function CreateThumb(id,name,type,copies){
var mainDiv = $('<div>').attr('class','col-sm-4 col-md-4');
var thumbNail = $('<div>').attr('class','thumbnail');
var caption = $('<div>').attr('class','caption');
var title = $('<h3>').text(name);
var title = $('<h5>').text(type);
var title = $('<h4>').text(copies);
var p = $('<p>');
caption.append(name);
caption.append(p);
caption.append(type);
thumbNail.append(caption);
mainDiv.append(thumbNail);
return mainDiv;
}
</script>
`.

After you've added the thumbnails use:
$(".thumbnail").onclick(function(){
document.location.href = newUrl;
}

You can listen to clicks with jQuery by using:
// Change the selector used below
$('#some-id-here').click(function(){
// Your code here
});
There's also another way, using "on". This might be more useful to you, because it also triggers on items added dynamically to the page, which looks to be your case.
// Change the selector used below
$('#some-id-here').on('click', 'img', function(){
// Your code here.
});
Also, you can select the document with $(document) (instead of #some-id-here) to apply it globally on your page, so every img tag would trigger this function.

Related

JQuery not able to get dynamic HTML element [duplicate]

This question already has answers here:
jQuery .on() event doesn't work for dynamically added element
(3 answers)
Closed 4 years ago.
I have this problem in JQuery and I can't seem to get past this issue.
I have a dynamically generated list of Li elements, and for each Li element I want to attach an On Hover so that a dropdown shows below the Li element. The catch is the Li elements are generated dynamically.
I have tried using .on("hover"), but nothing triggeres the event. The following is my code.
//On Init
$( document ).ready(function() {
generateList();
$(".app").on("hover", function () {
console.log('test'); //Does not trigger
});
$(".app").on("mouseenter", function () {
console.log('test'); //Does not trigger
});
});
//Load JSON file to generate app listing
function generateList(){
//Load JSON file
$.getJSON('json/adapters.json', function (json) {
var listCol = 5;
var ul = $('#container-apps');
//Generate app list from adapters.JSON
json.adapters.forEach(function (adapter) {
//Count adapter for no result function
adapterCount += 1;
var link = adapter.link;
var git = adapter.git;
var img = adapter.image;
var name = adapter.name;
//Appending the HTML elements
//List element
var li = $("<li>").attr("class", "app").appendTo(ul);
var a = $("<a>").attr({
"href": "javascript:void(0);",
"target":"_blank",
"class":"app-link",
}).appendTo(li);
var image = $("<img>").attr("src", img).appendTo(a);
var label = $("<div>").attr("class", "item-name black-font").html(name).appendTo(a);
//Hover element
var hoverContainer = $("<div>").attr("class", "hoverContainer").appendTo(li);
var hoverUL = $("<ul>").appendTo(hoverContainer);
var hoverPageLi = $("<li>").appendTo(hoverUL);
var hoverPageA = $("<a>").attr({"href": link, "target":"_blank", "class":"app-link"}).html("SDK").appendTo(hoverPageLi);
var hoverGitLi = $("<li>").appendTo(hoverUL);
var hoverGitA = $("<a>").attr({"href": git, "target":"_blank", "class":"app-link"}).html("Github").appendTo(hoverGitLi);
});
//Generate dummy box for responsive
for (var i = 0; i < (listCol); i++) {
$('<li class="item flex-dummy"></li>').appendTo(ul);
}
});
}
$(function () {
$(".app").hover(){
console.log('test'); //Does not trigger
}
})
Try this syntax:
$("body").on("click", ".app", function(){
//do something
});

'Close' button does not work in javascript

In the mobile version on my form appears 'Close' button.
Unfortunately, it does not work. I see a normal button, but when I click there is no reaction. In the javascript I load the file form-with-button.html to render form content in my all .html files.
<div id="form-with-button">
</div>
and use javascript to show and close.
//Onload show header and footer content
$("#header").load('header.html', function(){
$('#nav').affix({
offset: {top: $('#header').height()-$('#nav').height()}
});
});
$("#footer").load('footer.html');
$("#contact").load('footer-contact.html');
$("#form-with-button").load('form-with-button.html');
// Sticky Buttons Show Hide
$("#fix-quote, #fix-contact").on("click", function() {
var body = $("body");
var openPos= ["",""];
var id = $(this).attr("id");
var content = $("#"+id+"-content");
var property = (content.attr("class").toString().indexOf("left") > -1)? "left": "right";
if (!body.hasClass("bd_"+id)) {
openPos= [0,380]
var ele = $(this);
body.addClass("bd_"+id)
setTimeout(function(){
body.on("click.fix",function(ev) {
if($(ev.target).closest(".fixed-container").length == 0){
$(ele).click()
}
});
},10);
} else {
body.removeClass("bd_"+id).off("click.fix");
}
content.css("top","").show().css(property, openPos[0]);
$(this).css(property, openPos[1]);
});
// Mobile Requests Showhide
$("#fix-quote-mob, #fix-contact-mob").on("click", function() {
var id = $(this).attr("id").slice(0,-4);
var content = $("#"+id+"-content");
content.show()
setTimeout(function(){
content.css("top",0)
},10)
});
$(".fix-contact-close").on("click", function() {
var content = $(this).closest(".fixed-container");
content.css("top","").delay(400).hide(0);
});
Please help, why my button does not work?
You are trying to add a handler to an element created in a dynamic way, so you need to refactor your code in order to make it work:
$(document).on("click", ".fix-contact-close", function() {
var content = $(this).closest(".fixed-container");
content.css("top","").delay(400).hide(0);
});

Calling a javascript function with parameters from a dynamically created element

I'm trying to dynamically load pictures to a profile page like site from MySQL with PHP and
then add them to an unordered list with javascript. I would like each list item to also have
a like button, which upon clicking calls a javascript function, passing the image name as
its parameter. I've searched and found answers on how to call a function without passing it
any variables, but every time I add the image name to the function call, the console log reads
"undefined".
The pictures show up fine and the imgArray[i] is a string containing the file's name (e.g. photo.jpg)
But
console.log(imgArray[i])
in the onclick function reads undefined. I've also tried
like.setAttribute()
without any results.
function showGallery(imgArray) {
for(var i=0; i < imgArray.length; i++){
var list = document.getElementById("image-list"),
li = document.createElement("li"),
img = document.createElement("img"),
like = document.createElement("a");
img.src = "user_images/" + imgArray[i];
like.className = "button-like";
li.appendChild(img);
li.appendChild(like);
list.appendChild(li);
like.href = "javascript:void(0);";
like.onclick = function() {
console.log(imgArray[i]);
addLike(imgArray[i]);
};
}
}
function addLike(img) {
console.log("Liking.. " + img);
$.ajax({
url: 'like.php',
type: 'POST',
data: {
'photo': img
},
success: function(likes){
console.log(likes);
}
});
}
The problem is that by the time the click event fires, imgArray[i] doesn't exists.
try doing it like this...
like.href = "javascript:void(0);";
like.imgArray = imgArray[i];
like.onclick = function() {
console.log(this.imgArray);
addLike(this.imgArray);
};
Hope that helps

JQuery-Javascript looping issue

I'm working on a banner for a website and I need it to loop through the images. My problem is that it plays through the images once and then stops. I've tried everything that I can think of with no luck. I'm sure this is simpler than I'm making it, but some help would be greatly appreciated. The latest version is below.
$(document).ready(function(){
// Variables required by script
var currentimage;
// Load Gallery XML file
$.ajax({
url: 'banner.xml',
type: 'GET',
dataType: 'xml',
error: function(){
alert('Error loading XML document');
},
success: function(xmlData){
// do something with xml
setupImages(xmlData);
}
});
// Display images
function setupImages(xmlData) {
// read xml and use it to populate page
//get first image
currentimage = $(xmlData).find("image:first");
// Fade in image after countdown
var t = setTimeout(function(){showNewImage()}, 1000);
}
// Display the image, caption, rating and label
function showNewImage() {
var image = $(currentimage).find("path").text();
var caption = $(currentimage).find("caption").text();
$("#imagelabel").removeClass("active");
// Fade out current image and fade in new image
$("#bannerimgholder").animate({opacity:0},500,
function(){
$(this).css({"backgroundImage":"url("+image+")"}).animate({opacity:1},1000,
function(){
$("#imagelabel").addClass("active");
});
});
// Add caption
$("#imagelabel").text(caption);
var to = setTimeout(function(){getNextImage()}, 5000);
}
function getNextImage(){
var tmp = $(currentimage).next();
if ($(tmp).find("path").text()=="") {
currentimage = $(xmlData).find("image:first");
} else {
currentimage = tmp;
}
showNewImage();
}
});
Your code is using next(), which will return nothing once you reach the last image.
You need to use a different test to close the loop, for example:
tmp.length==0
Note that tmp is already a jQuery object, so you don't need to wrap it in $().
This page offers an example of nextOrFirst() function that does what you want.
Here is a solution that I came up with.
First I added an element to the end of my xml file with just a 'path' attribute of "last".
Next, I add the following variable to save the path name of the first element:
var imagepathtext;
Then, in the setupImages(xmlData) function I added the following:
imagepathtext = $(currentimage).find("path").text();
Lastly, I changed the getNextImage() function from
function getNextImage(){
var tmp = $(currentimage).next();
if ($(tmp).find("path").text()=="") {
currentimage = $(xmlData).find("image:first");
} else {
currentimage = tmp;
}
showNewImage();
}
to
function getNextImage(){
var tmp = $(currentimage).next();
if ($(tmp).find("path").text()=="last") {
while ($(tmp).find("path").text()!=firstimagepath)
{
var tmp1 = $(tmp).prev();
tmp = tmp1;
}
currentimage = tmp;
} else {
currentimage = tmp;
}
showNewImage();
}
And just like magic it loops correctly now!

Detecting Href Is Clicked

I'm trying to detect if certain element is clicked on onbeforeunload. I can't get it to work. Below is examples of the Javascript code and HTML code on the project (Please note that I have no control over the HTML element as it is not my site)
function checkLeave() {
var p = document.getElementByElementById('yeah');
if (p.href.onclick) {
//do something
}
else {
//do something else
}
}
window.onbeforeunload = checkLeave;
HTML CODE
//The goSomewhere goes to another page
<a id="yeah" href="javascript:goSomewhere();">
<img src="smiley.png">
</a>
Thanks in advance,
J
What you need to do is bind an event handler to each on the page.
This can be done with the following:
// Select all links
//var allLinks = document.querySelectorAll('a[href]');
var allLinks = document.links;
// Bind the event handler to each link individually
for (var i = 0, n = allLinks.length; i < n; i++) {
//allLinks[i].addEventListener('click', function (event) {});
allLinks[i].onclick = function () {
// Do something
};
}
You are testing for the presence of the onclick property to the <a> tag. It isn't present in the markup. Rather than using the onclick, the markup calls a script as the element's href. So you need to look for a script in the href instead:
var p = document.getElementByElementById('yeah');
if (p.href.indexOf("javascript") === 0) {
//do something
}
else {
// do something else
}
Maybe something like this? (just the idea)
document.getElementById('yeah').onclick = function() {
clicked = this.href;
};

Categories

Resources