.click() jQuery function works for one ID but not variable - javascript

I have this code in my js file and basically what I want to test out is, if the user clicks on a certain button (which has ID of admin).
I want it to bring up a closeButton which is png image and then when the user clicks this again it should disappear. To test of the button functions are responsive I have put alerts in the functions.
Clicking on the initial button works, the function finds the corresponding ID, makes the alert("jQuery Worked") line and brings up the closeButton image.
However when I click on the close button nothing happens (we expect here that the alert("hiii") would work but it doesn't. I have looked online and found that my code needed to be in a $(document).ready(function() {} function which it is but it isn't working. I also tried to use the ID of the image to make the closeButton image disappear but that didn't work either. So I have tried just using the $closeButton variable which I thought for usre should work but doesn't. Why?
.js file
var $closeButton = $("<img>");
$(document).ready(function() {
$("#admin").click(function (event) {
var $overlay = $("<div id='overlay'> </div>");
var $closeButton = $("<img class='classMe' id='closeButtonID' src='https://s23.postimg.org/ouup1ib6z/close_button.png'></img>");
$("body").append($overlay);
$overlay.append($closeButton);
alert("jQuery worked");
});
$closeButton.click(function() {
alert("hiiii");
});
});

you looking for Event delegation.
Event delegation refers to the process of using event propagation
(bubbling) to handle events at a higher level in the DOM than the
element on which the event originated. It allows us to attach a single
event listener for elements that exist now or in the future. Inside
the Event Handling Function.
$(document).on('click', '#closeButtonID', function() {
alert('hiii');
});

Do this:
$(document).ready(function() {
$("#admin").click(function (event) {
var $overlay = $("<div id='overlay'></div>");
var $closeButton = $("<img id='closeButtonID' src='https://s23.postimg.org/ouup1ib6z/close_button.png'></img>");
$("body").append($overlay);
$overlay.append($closeButton);
alert("jQuery worked");
});
$(document).on('click', '#closeButtonID', function() {
alert('hi');
});
});

Not a good way to do this but it's a different way to solve the problem , Hope it will help you :
var $closeButton = $("<img>");
$(document).ready(function() {
$("#admin").click(function (event) {
var $overlay = $("<div id='overlay'> </div>");
var $closeButton = $("<img class='classMe' id='closeButtonID' src='https://s23.postimg.org/ouup1ib6z/close_button.png'></img>");
$("body").append($overlay);
$overlay.append($closeButton);
alert("jQuery worked");
close();
});
function close(){
$('#closeButtonID').click(function() {
alert("hiiii");
});
}
});
JSFIDDLE

Related

Jquery on php in div box not working

I have an main php that load a php into a div box via a dropdown list.
The loaded php contains a table. There is jquery in it that does an alert on row clicked.
$(document).ready(function() {
$('#newsTable tr').click(function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
});
But after it is loaded into the div, the script is not firing
use Event delegation to attach event. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(document).ready(function() {
$(document).on('click','#newsTable tr',function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
}); // End
There is something with event delegation. Try using this code :
$('id_Or_Class_container_hold_the_php_data').on('click', 'tr', function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
replace
(document).ready(function() {
with
$(document).ready(function() {
try this
jQuery(document).ready(function($) {
$('#newsTable tr').click(function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
});
I think you need to use live query, instead of your click event u can use following.
$('#newsTable tr').on('click',function()
Use below code..i think its working properly.
$(document).ready(function() {
$("#newsTable").on('click','tr',function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
});

jQuery doesn't recognize a class change

Ok, I have a edit button, when I press on it, it changes to "done" button.
It's all done by jQuery.
$(".icon-pencil").click(function() {
var pencil = $(this);
var row = $(this).parent('td').parent('tr');
row.find('td').not(":nth-last-child(2)").not(":last-child").each(function() {
$(this).html("hi");
});
pencil.attr('class', 'icon-ok-sign');
});
// save item
$(".icon-ok-sign").click(function() {
alert("hey");
});
When I press on a "edit" (".icon-pencil") button, its classes change to .icon-ok-sign (I can see in chrome console),
but when I click on it, no alert shown.
When I create a <span class="icon-ok-sign">press</span> and press on it, a alert displays.
How to solve it?
Try using $( document ).on( "click", ".icon-ok-sign", function() {...
Thats because you can not register click-events for future elements, you have to do it like this:
$(document).on('click', '.icon-ok-sign', function() {
alert('hey');
});
This method provides a means to attach delegated event handlers to the
document element of a page, which simplifies the use of event handlers
when content is dynamically added to a page.
Use following script:
$(document).on('click','.icon-ok-sign',function(){
alert("hey");
});
Try this:
$(".icon-pencil").click(function() {
var pencil = $(this);
var row = $(this).parent('td').parent('tr');
row.find('td').not(":nth-last-child(2)").not(":last-child").each(function() {
$(this).html("hi");
});
pencil.removeAttr('class').addClass('icon-ok-sign');
});
// save item
$(".icon-ok-sign").click(function() {
alert("hey");
});

jquery Multiple alerts

How can i count element once?
Right now, evert time, when i click #totalItems, alert is rised as many times, as many element are in #photoId ?
<script type="text/javascript">
$(document).ready(function(){
photoId = $('.photoId');
totalItems = $('#totalItems');
$(photoId).on('click', function(){
//alert ($(this).html());
$(this).clone().appendTo(totalItems);
$('#count').on('click', function(e){
sizes = (totalItems.children().size());
alert (sizes);
});
$('#count').off('click', function(e){
sizes = (totalItems.children().size());
alert (sizes);
});
});
});
</script>
Replace this line :
$(photoId).on('click', function(){
By :
photoId.on('click', function(){
You are attaching $('#count').on('click', function() { ... handler on every click on .photoId. Make sure it is only done once from within the document's ready event.
In case your #count is actually inside the DOM being cloned, you need to
get rid of ID and replace it with class.
bind event to the top level container with CSS filter
I.e. something like this:
$("#totalItems").on("click", ".count", function() { ...

Restore page content and retain event listeners

How would you "save" a page somewhere (on the client), then restore it, with all its event listeners intact?
I have a sample at http://jsfiddle.net/KellyCline/Fhd55/ that demonstrates how I create a "page", save it and go to a "next" page on a button click, and then restore the first page on another button click, but now the first page's click listeners are gone.
I understand that this is due to the serialization that html() performs, so, obviously, that's what I am doing wrong, but what I'd like is a clue to doing it right.
This is the code:
var history = [];
$(document).ready(function () {
var page1 = $(document.createElement('div'))
.attr({
'id': 'Page 1'
}).append("Page ONE text");
var nextButton = $(document.createElement('button'));
nextButton.append('NEXT');
nextButton.on('click', function () {
CreateNextPage();
});
page1.append(nextButton);
$("#content").append(page1);
});
function CreateNextPage() {
history.push( $("#content").html( ) );
$("#content").html( 'Click Me!');
var page1 = $(document.createElement('div'))
.attr({
'id': 'Page 2'
}).append("Page TWO text");
var nextButton = $(document.createElement('button'));
nextButton.append('NEXT');
nextButton.on('click', function () {
CreateNextPage();
});
var prevButton = $(document.createElement('button'));
prevButton.append('PREVIOUS');
prevButton.on('click', function () {
GoBack();
});
page1.append(nextButton);
page1.append(prevButton);
$("#content").append(page1);
}
function GoBack() {
$("#content").html( history[history.length - 1]);
history.pop( );
}
and this is the html:
Click Me!
I think this is best solved via event delegation. Basically, you encapsulate content that you know you are going to refresh within a wrapper element and bind your listeners to that. The jQuery .on() method allows you to pass a selector string as a filter and will only trigger the handler if the originating element matches. Give your buttons a class or something to get a handle on them and then bind them up above. This article has some examples.
$( '#content' ).on( 'click', 'button.next', createNextPage )
for instance.

Stoping a link from executing it's href path

Hi I am trying to stop a link from executing it's default action , but I seem to have no luck.Here is my code:
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
});
var lightbox = {
init : function(actionString){
$("<div id='lightbox-background'></div>").appendTo("body");
$("<div id='lightbox'></div>").appendTo("body");
$("<p></p>").appendTo("#lightbox");
$("<a href='#' id='ok'>OK</a>").appendTo("#lightbox");
$("<a href='#' id='cancel'>Cancel</a>").appendTo("#lightbox");
}
}
I hoped that if I used e.preventDefault it would stop the link from from going to it's href path but it did not work.Am I doing something wrong?
EDIT: I just noticed that if I remove the call for the lightbox object from the click event handler the e.preventDefault() works.
Your problem is in this line:
var lightbox = $("#lightbox");
in onclick callback function hide
variable name is the same as name of global lightbox object defined outside click callback. Local variable mentioned above simply override global variable inside that function scope. Basically, you are calling init of $("#lightbox"):
$("#lightbox").init("....")
Not sure what are you doing, but try to update your code like this:
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightboxElement = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
});
Besides, calling
var container = $("#lightbox-background");
var lightboxElement = $("#lightbox");
at the first time, you will get an empty set of elements as init method is not executed at that moment and elements you are looking for are not created yet.
Try if it works
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
return false;
});
Have you tried it above the vars declared:
$("a.delete").on("click", function (e) {
e.preventDefault();
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
});
Just noticed that you have missed a ';' at closing here:
var lightbox = {
init : function(actionString){
$("<div id='lightbox-background'></div>").appendTo("body");
$("<div id='lightbox'></div>").appendTo("body");
$("<p></p>").appendTo("#lightbox");
$("<a href='#' id='ok'>OK</a>").appendTo("#lightbox");
$("<a href='#' id='cancel'>Cancel</a>").appendTo("#lightbox");
}
}; //<----this one
Example for a link like:
google
use javascript with jQuery
$("a").click(function(e){e.preventDefault(); return false;});
this will not redirect any link on the page :)
or in given case it will be like
$("a.delete").click(function(e){e.preventDefault(); return false;});
Note: Added e.preventDefault(); to prevent the event from triggering.

Categories

Resources