Why the click event will not working in jQuery? - javascript

I have a html and jQuery code in which there are two img dynamically created and after ajax I'm applying click events on the images but the click events not working. Means they show nothing. that the imae is clicked or not. I'm showing my code following:-
<div id="images">
<img id="image/5c07a4337c76881db6bf9a7f" src="data:image/jpeg;base64,/9j/4AA.....>
<img id="image/5c07a4337c76881db6bf9a7d" src="data:image/jpeg;base64,/9j/4AA.....>
</div>
$( document ).ready(function() {
$.ajax({
url: "/api/v1/get-all-upload-image?sortBy=date",
type: "GET",
success: function(response){
console.log(response);
$.ajax({
url : "/api/v1/base-strings",
type:"GET",
success:function(response){
console.log(response.response.data)
for (i= 0; i < response.response.data.length; i++){
console.log(response.response.data[i])
var base64_string = response.response.data[i].data;
var img = document.createElement("img");
img.setAttribute("id", "image/"+response.response.data[i].files_id);
img.setAttribute("onclick", "addListeners()");
// added `width` , `height` properties to `img` attributes
img.style.width ='340px';
img.style.height ='194px';
img.style.margin = '50px';
img.style.cursor = 'pointer';
img.src = "data:image/jpeg;base64," + base64_string;
var preview = document.getElementById("images");
preview.appendChild(img);
}
}
});
}
});
function addListeners () {
$('img[id^="image"]').on('click', function(){
var val = $(this).attr('id').split('/');
id= val[val.length - 1]
});
}
$('img[id^="image"]').click(function(){
alert("hello")
})
$('img[id^="image"]').on('click', function(){
var val = $(this).attr('id').split('/');
id= val[val.length - 1]
});
});
Error
Uncaught ReferenceError: addListeners is not defined
at HTMLImageElement.onclick
What is the problem with the code why it is not working?

Listen Just do it like I said. Paste the below code after your first ajax call:-
$('body').on('click','img', function(){
alert("I'm here");
});
Hope Works well :)

Related

trying to appendChild and removeChild at the same time

$('#submit').on('click', function(){
$.ajax({
type:'GET',
url:'http://www.boredapi.com/api/activity/',
success: function(data){// my data
console.log(data);
console.log(data.activity);
var body = document.getElementById('add');
var newDiv = document.createElement('div');
newDiv.innerText = data.activity;
console.log(newDiv); //my data
console.log(body);
var num = 0;
body.appendChild(newDiv);
$('#submit').on('click', function(){
body.removeChild(newDiv);
})
}
})
})
I am trying to add one div with one click, and with a second click remove the first div and add a new div in its place. Right now, I figured out a way to have another eventListner to make a second 'click' remove the first div and add a second but the third click it'll go right back to storing every div with each click. I thing a loop between both eventListner will work but not sure how to make that work logically. I hope I've explained this well enough. Thank you in advance for your help.
$('#submit').on('click', function(){
$.ajax({
type:'GET',
url:'http://www.boredapi.com/api/activity/',
success: function(data){// my data
console.log(data);
console.log(data.activity);
var body = document.getElementById('add');
var newDiv = document.createElement('div');
newDiv.innerText = data.activity;
console.log(newDiv); //my data
console.log(body);
$("#add").empty()
body.appendChild(newDiv);
}
You can use replaceWith() in this case:
Like:
var body = document.getElementById('add');
var newDiv = document.createElement('div');
var old_div = document.querySelectorAll('#add>div') !== null;
if(!old_div){
body.appendChild(newDiv);
} else {
old_div.replaceWith(newDiv);
}
If third line is not understandable, see here.
Overall, your code will look sthg like this:
$.ajax({
type:'GET',
url:'http://www.boredapi.com/api/activity/',
success: function(data){// my data
console.log(data);
console.log(data.activity);
var body = document.getElementById('add');
var newDiv = document.createElement('div');
var old_div = document.querySelectorAll('#add>div') !== null;
newDiv.innerText = data.activity;
if(!old_div){
body.appendChild(newDiv);
} else {
old_div.replaceWith(newDiv);
}
})
}
})
*Note:- success, error, complete are depreciated are removed from version 3.0. Refs
You need to check if the div exists before removing it. The first time the form is submitted there is no div, so it's going to be created and then the new click event will be binded. Then when you click again that div already exists, so you are creating it again, before removing the previous one. I suggest you to add an id to the div in the moment you create it
I would do:
$('#submit').on('click', function () {
$.ajax({
type: 'GET',
url: 'http://www.boredapi.com/api/activity/',
success: function (data) {
var body = $('#add');
if($('#NewDiv')){
body.removeChild($('#NewDiv'))
}
// my data
console.log(data);
console.log(data.activity);
var newDiv = $(document.createElement('div'));
newDiv.attr('id', 'NewDiv');
newDiv.innerText = data.activity;
console.log(newDiv); //my data
console.log(body);
var num = 0;
body.appendChild(newDiv);
}
})
})
This solution stores newDiv and ensures that it's not null before it's removed:
<script>
var newDiv = null;
var body = document.getElementById('add');
$('#submit').on('click', function () {
if (newDiv) {
body.removeChild(newDiv);
}
$.ajax({
type: 'GET',
url: 'http://www.boredapi.com/api/activity/',
success: function (data) {// my data
console.log(data);
console.log(data.activity);
newDiv = document.createElement('div');
newDiv.innerText = data.activity;
console.log(newDiv); //my data
console.log(body);
var num = 0;
body.appendChild(newDiv);
}
})
});
</script>
Here is a solution on how you can remove and append divs using clicks, I have added a counter to demonstrate the change, you can accustom this solution to fit your need
let body = document.getElementById('add');
let olddiv = document.getElementById('olddiv');
let divs=document.getElementsByClassName("div");
flag = false
counter = 0
$('#submit').on('click', function() {
if (!flag) {
addiv(counter)
console.log("divadded ",divs)
counter++
flag = true
} else {
addNewDiv(counter)
counter++
flag = false
}
})
function addiv(counter) {
while (body.hasChildNodes()) {
body.removeChild(body.firstChild);
}
var newDiv = document.createElement('div');
newDiv.id = `olddiv${counter}`
newDiv.className = "div"
newDiv.innerText = counter;
body.appendChild(newDiv);
}
function addNewDiv(counter) {
while (body.hasChildNodes()) {
body.removeChild(body.firstChild);
}
addiv(counter)
console.log("removed",divs)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add"></div>
<button id="submit">changeDiv</button>

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

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.

Error FB.XFBML.parse comment box facebook

Hi I have this javascript code:
$.fn.imagesLoaded = function () {
$imgs = this.find('img[src!=""]');
if (!$imgs.length) {return $.Deferred.resolve().promise();}
var dfds = [];
$imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.src = this.src;
});
return $.when.apply($,dfds);
}
var disc = function(div,of){
$(div).hide();
$('#loading').show();
var ajax = $.ajax({url : of, type : "GET", cache: false});
ajax
.done(function(response){
Commons.sorDone(div, response);
FB.XFBML.parse(document.getElementById('.fb-comments'));
twttr.widgets.load();
})
.fail(function(){
Commons.sorFail(div);
});
}
Commons = {
sorDone : function (div, response) {
$(div).html(response).imagesLoaded().then(function(){
$('#loading').hide();
$(div).show();
});
},
}
The code does is load content via a button in a div dynamically. While charging the content shows a gif preload.
Well, that content is no social buttons facebook and twitter and box of facebook comments also show that in order to be parsed with FB.XFBML.parse
So far so good, but the problem is that sometimes appear facebook comments and sometimes the empty space and comments are not displayed.
where it could be wrong?
I have solved just when placing below shows the div at the end.
For if someone helps. No longer fails, it will always spot the parse.
$.fn.imagesLoaded = function () {
$imgs = this.find('img[src!=""]');
if (!$imgs.length) {return $.Deferred.resolve().promise();}
var dfds = [];
$imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.src = this.src;
});
return $.when.apply($,dfds);
}
var disc = function(div,of){
$(div).hide();
$('#loading').show();
var ajax = $.ajax({url : of, type : "GET", cache: false});
ajax
.done(function(response){
Commons.sorDone(div, response);
})
.fail(function(){
Commons.sorFail(div);
});
}
Commons = {
sorDone : function (div, response) {
$(div).html(response).imagesLoaded().then(function(){
$('#loading').hide();
$(div).show();
FB.XFBML.parse(document.getElementById('.fb-comments'));
twttr.widgets.load();
});
},
}

Adding event handler to non-existent class?

I've seen questions that relate to non-existent elements, but not non-existent classes. Here's what I want to do. When a button of class "see_answer" is clicked, I want to remove the class and replace it with "see_question". However, my click function for a button, once its class is "see_question", is not running. I have tried $(document).on("click", ".see_question", function(event ) and I have tried $(".see_question").on("click", function(event) {etc.... Thanks for the help! My code is below:
$(document).ready(function() {
// initialize variables
var lang = "javascript";
var qno = 1;
var prevText; // holds question/answer
var language = lang + ".html";
// set up tabs, and keep track of which one is clicked
$("#myTabs").tabs({
activate: function (event, ui) {
var active = $("#myTabs").tabs("option", "active");
lang = $("#myTabs ul > li a").eq(active).attr("href");
lang = lang.replace("#", "");
}
});
/* REMINDERS
actual qa part: blah_language
*/
// set up question
$.ajax({
url: language,
dataType: "html",
success: function(data) {
$("#blah_"+lang)
.text($(data).find("#1").text());
},
error: function(r) {
alert("whoops, error in initialization");
}
});
$(".next_question").on("click", function(event) {
event.preventDefault();
var id = $(this).attr("id").replace("next_question_", "");
var language = id + ".html";
var doc = "#blah_" + id;
$.ajax({
url: language,
dataType: "html",
success: function(data) {
var num = "#" + qno;
$(doc)
.text($(data).find(num).text());
qno = qno + 1;
},
error: function(r) {
alert("whoops");
}
});
prevText = "";
});
// SHOW ANSWER
$(".see_answer").on("click", function(event) {
event.preventDefault();
var id = $(this).attr("id").replace("see_answer_", "");
var prev = "#blah_" + id;
var answers = id + "_answers.html";
// Save the question
prevText = $(prev).text();
var obj = $(this);
$.ajax({
url: answers,
dataType: "html",
success: function(data) {
var num = "#" + 3;
$(prev)
.text($(data).find(num).text());
},
error: function(r) {
alert("whoops");
}
});
obj.val("See Question");
obj.removeClass("see_answer");
obj.addClass("see_question");
event.stopPropagation();
});
$(document).on("click",".see_question", function(event) {
event.preventDefault();
obj = $(this);
event.preventDefault();
var id = $(this).attr("id").replace("see_answer_", "");
var prev = "#blah_" + id;
$(prev).text(prevText);
obj.val("See Answer");
obj.removeClass("see_question");
obj.addClass("see_answer");
});
})
Click handling for .see_question elements is delegated to document. For .see_answer elements, a click handler is attached directly. Therefore, swapping the class names will have an undesirable effect.
when see_answer is in force, a click will trigger the "see_answer" handler.
when see_question is in force, a click will trigger the "see_question" handler AND the "see_answer" handler, which is still attached.
There's a number of ways to do this properly. From where you currently are, the simplest solution is to delegate click handling of .see_question and .see_answer elements to document.
$(document).on("click", ".see_answer", function(event) {
...
});
$(document).on("click", ".see_question", function(event) {
...
});
Combine the 2 handlers and figure out which version it is by hasClass() before you change the classes around
$(document).on("click", ".see_question, .see-answer", function(event ){
var $btn =$(this), isAnswer = $btn.hasClass('see_answer');
// we know which one it is so can switch classes now
$btn.toggleClass('see_answer see_question');
if(isAnswer){
/* run code for answer version */
}else{
/* run code for question version */
}
});

redirecting to other page with value in javascript via click

I want to create a Javascript file to do these operations:
Pass the current link to the other page
Click on hypertext or image that is created dynamically in JavaScript file to redirect
Just I want to have a Javascript link in the html body and not other thing same this :
<div>
<script type="text/javascript" src="JScript.js"></script>
</div>
And in the JavaScript file I have these:
var DivTag = document.createElement("Div");
DivTag.setAttribute('ID', 'MyDivTagID');
$(document).ready(function () {
$("$MyDivTagID").click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + window.location;
});
});
This is not working. Please help me.
Several issues
you never added the div to the page
you used $ instead of # to access the div by ID
you do not consistently use jQuery
Plain JS: DEMO HERE
window.onload=function () {
var DivTag = document.createElement("div");
DivTag.setAttribute('id', 'MyDivTagID');
DivTag.innerHTML="Click";
DivTag.onclick = function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
}
document.body.appendChild(DivTag);
}
Using linked image:
window.onload=function () {
var DivTag = document.createElement("div");
DivTag.setAttribute('id', 'MyDivTagID');
var anchor = document.createElement("a");
anchor.href="#";
anchor.onclick = function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
}
var img = document.createElement("img");
img.src="image.gif";
img.style.border="0";
anchor.appendChild(img);
DivTag.appendChild(anchor);
document.body.appendChild(DivTag);
}
jQuery: DEMO HERE
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>');
$("#MyDivTagID").click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
A small change to the jQuery code from mplungjan:
Change:
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>').click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
To:
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>').find('#MyDivTagID').click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
If you output e.currentTarget from the anonymous click handler function you get body since the event handler was attached to the body in mplungjan's solution. All I did was add .find('#MyDivTagID') directly after the .append() function so the click handler gets attached to the div and not the body.

Categories

Resources