jQuery not executing code for new element with new id - javascript

I have an image, and when I click on it I want it to change to a different image and change its ID as well. Then when I click on this new image, it reverts back.
$(document).ready(function(){
$("#name_edit").click(function(){
$(this).attr("src", "img/tick.png");
$(this).attr("id","name_confirm");
});
$("#name_confirm").click(function(){
$(this).attr("src", "img/edit.png");
$(this).attr("id","name_edit");
});
});
I have successfully done the first step, going from #name_edit to #name_confirm. However, not the reverse.
How do I go about solving this?
My suspicion is that since I'm using (document).ready, jQuery is preparing itself for elements already on the page. However, the element with the ID name_confirm does not exist until the image is clicked on.
Thanks.

The element that you are working on is always the same...
$(document).ready(function(){
// use just the first id value to find it in the DOM
$("#name_edit").click(function(){
var item = $(this);
var id = item.attr('id');
if(id === 'name_edit') {
return item
.attr("src", "img/tick.png")
.attr("id","name_confirm")
;
}
return item
.attr("src", "img/edit.png")
.attr("id","name_edit")
;
})
;
});

I think you have chosen bad solution for your problem.
1) Why your code doesn't work:
You bind 2 events only 1 time, whne your document loaded. So, jquery finds #name_edit element and bind onclick event on it. But jquery cannot find #name_confirm element, because it doesn't exists on document ready)
In your code you should bind 1 onclick event, but have some attr (for example class for checking your state).
Something like:
<img id="main_image" class="name_edit"/>
<script>
var img_paths = ["img/tick.png", "img/edit.png"]
var img_index = 0;
$("#main_image").click(function(){
if($(this).attr("class") == "name_edit"){
$(this).attr("src", "img/tick.png");
$(this).attr("class","name_confirm");
}
else{
$(this).attr("src", "img/edit.png");
$(this).attr("class","name_edit");
}
});
</script>
Other solutions: You can create 2 images and show/hide them.
Or use styles with background attr. With pseudoclasses or classes.
Also you can store image pathes in array and tick array index on click.
Something like:
var img_paths = ["/content/img1.png", "/content/img2.png"]
var img_index = 0;
$("#main_image").click(function(){
$(this).src = img_paths[img_index];
img_index = !img_index;
})

It is not working because you are referencing the same elements, try this:
(function(window, document, $, undefined){
$("#name_edit").on("click", function(){
var self = $(this);
if(self.attr("id") === "name_edit") {
self.attr("src", "img/tick.png");
self.attr("id", "name_confirm");
} else {
self.attr("src", "img/edit.png");
self.attr("id", "name_edit");
}
});
})(this, this.document, jQuery);
Also for easier to understand code you could use classes like this:
(function(window, document, $, undefined){
$(".name_edit").on("click", function(){
var self = $(this);
if(self.hasClass("name_edit")) {
self.attr("src", "img/tick.png");
self.removeClass("name_edit").addClass("name_confirm");
} else {
self.attr("src", "img/edit.png");
self.removeClass("name_confirm").addClass("name_edit");
}
});
})(this, this.document, jQuery);
To simplify replacing classes you could even add your own $.fn.replaceClass(); like this:
jQuery.fn.replaceClass = function(classA, classB) {
this.removeClass(classA).addClass(classB);
return this;
};
Then use it like this:
(function(window, document, $, undefined){
$(".name_edit").on("click", function(){
var self = $(this);
if(self.hasClass("name_edit")) {
self.attr("src", "img/tick.png");
self.replaceClass("name_edit", "name_confirm");
} else {
self.attr("src", "img/edit.png");
self.replaceClass("name_confirm", "name_edit");
}
});
})(this, this.document, jQuery);

I can confirm what the others said.. the jquery gets run on document ready, but doesn't get updated subsequently - so it basically gets the correct element from the dom, and assigns the click event. It has no event for the name_confirm.
so this code does nothing...
$("#name_confirm").click(function(){
$(this).attr("src", "img/edit.png");
$(this).attr("id","name_edit");
});
See it not work in this instructive jsfiddle
Of course does the id need to change? is it possible to use for example a specific class for the img? then you could make the second click bind on the class instead... for example see this working example, which still changes the src and id...

Try On method:
$(document).on('click', '#name_edit', function(){
$(this).attr("src", "img/tick.png");
$(this).attr("id","name_confirm");
});
$(document).on('click', '#name_confirm', function(){
$(this).attr("src", "img/edit.png");
$(this).attr("id","name_edit");
});

Related

Jquery rename content insite a tag and confirm it

The User should be able to change the Name and then confirm the change. I'm not able to archive it with this code as when I click confirm, it returns like before.
What am I missing?
Any better way to put this together (which I'm sure there's one) ?
Please check the demo where you can also see the changeElementTypefunction
http://jsfiddle.net/dLk6E/
js:
$('.replace').on('click', function () {
$("h2").changeElementType("textarea");
$('.replace').hide();
$('.confirm').show();
//Confermation of the change
$('.confirm').bind('click', function () {
$('.replace').show();
$('.confirm').hide();
$("textarea").changeElementType("h2");
});
if ($('textarea:visible')) {
$(document).keypress(function (e) {
if (e.which == 13) {
alert('You pressed enter!');
$("textarea").changeElementType("h2");
$('.replace').css('opacity', '1');
}
});
}
});
Here are your updated code and working fiddle http://jsfiddle.net/dLk6E/
(function($) {
$.fn.changeElementType = function(newType) {
var attrs = {};
$.each(this[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
this.replaceWith(function() {
return $("<" + newType + "/>", attrs).append($(this).contents());
});
}
})(jQuery);
$('.replace').on('click', function (){
$("h2").changeElementType("textarea");
$('.replace').hide();
$('.confirm').show();
//Confermation of the change
$('.confirm').on('click', function(){
$('.replace').show();
$('.confirm').hide();
// you are missing this
$('.replaceble').html($("textarea").val());
$("textarea").changeElementType("h2");
});
if ($('textarea:visible')){
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
$("textarea").changeElementType("h2");
$('.replace').css('opacity','1');
}
});
}
});
updated
jsfiddle.net/dLk6E/1
I think your code is right but you need to use the value you're entering when replacing it. So the confirmation binding would be something like this (fetching it, and then using it to update the textarea before "transforming" it into an h2 tag.
$('.confirm').bind('click', function(){
var valueEntered = $('textarea').val();
$('.replace').show();
$('.confirm').hide();
$("textarea").html(valueEntered).changeElementType("h2");
});
You could be using .on for this as well as of jQuery 1.7 is prefered to .bind.
Another thing I would suggest is whenever you struggle with something like this just put in google (or whatever...) exactly what you want, in this case "jquery get value of input" will get asw first result the jquery documentation
This way you won't forget it ;)
Update: Maybe a small detail but in the binding I use it would be more efficient to just hit $('textarea') once, so it would be something like this. Something that you may keep in mind (not really an issue here), better to store in a variable than hit the DOM several times.
$('.confirm').on('click', function(){
var $textarea = $('textarea');
$('.replace').show();
$('.confirm').hide();
$textarea.html($textarea.val()).changeElementType("h2");
});
jsfiddle

Define a function globally in jQuery

I have some simple jQuery code, and it has a problem. The menu handler function doesn't work at all.
var clicked = false;
$(document).ready(function(){
$TemplateMenu= $('<p class="paragraph">texxt</p>');
$('.TemplateMaker').click();
this.menuhandler();
});
});
function menuhandler(){
if(clicked == false){
$(this).after($TemplateMenu);
clicked = true;
}
else{
$TemplateMenu.remove();
clicked = false;
}
For some reason, the function works if I put it directly inside click() like this:
$('.TemplateMaker').click(function(){
if(clicked == false){
$(this).after($TemplateMenu);
clicked = true;
}
else{
$TemplateMenu.remove();
clicked = false;
}
});
});
What is wrong with this code? Did I define the function wrong or do I need something special if the function contain jQuery elements?
Thanks for the help :-)
Edit:
I edit the code to include your guys suggestions, its stile doesn't seem to work.
code:
var clicked = false;
$(document).ready(function(){
$TemplateMenu= $('<p class="paragraph">texxt</p><p class="p2">texxt</p>');
$('.TemplateMaker').click(menuHandler($(this)));
});
function menuHandler(obj){
if(clicked == false){
$(obj).after($TemplateMenu);
clicked = true;
}
else{
$TemplateMenu.remove();
clicked = false;
}}
I notic now that the jquery throw this "event.returnValue is deprecated. Please use the standard event.preventDefault() instead. ", but I don't know how its contact to my script.
$('.TemplateMaker').click();
this.menuhandler();
});
Try replacing this.menuhandler(); with just menuhandler(); as shown below:
$('.TemplateMaker').click();
menuhandler();
});
Edit: In response to your comment. Try using this instead of $(this) in the menuhandler() of your original code.
You probably want the menuHandler function to fire when someone clicks on the button? Then you can simply change your code as follows:
$('.TemplateMaker').click(menuHandler);
Edit:
You basically have two options:
Option1:
You don't have to pass $(this) change your code to this (make sure you remove the parameter in the menuHandler function if you choose this approach):
$(document).ready(function(){
$TemplateMenu= $('<p class="paragraph">texxt</p><p class="p2">texxt</p>');
$('.TemplateMaker').click(menuHandler);
});
Option2:
Or if you want to pass $(this) you can do something like this (keep the parameter in the menuHandler function if you choose this approach):
$(document).ready(function(){
$TemplateMenu= $('<p class="paragraph">texxt</p><p class="p2">texxt</p>');
$('.TemplateMaker').click(function() {
menuHandler($(this));
});
});

Why is jQuery .click() is skipped over?

I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});

Combining jquery functions - on() hover/mouseenter/mouseleave

I have a series of elements (lets call them '.my-elements') - some load on document ready, while others are loaded later via a pagination script.
I would like to set a variable according to whether or not the mouse is over these elements. The code below works, but I suspect there is a better way... Can I do this so I only have to reference the DOM once?
$(document).on('mouseenter','.my-elements', function(){
mouse_is_inside = true;
});
$(document).on('mouseleave','.my-elements', function(){
mouse_is_inside = false;
});
Thanks!
You can bind to both together and check the event.type:
$(document).on('mouseenter mouseleave', '.my-elements', function (ev) {
mouse_is_inside = ev.type === 'mouseenter';
});
Or, if you want to keep them separate, .on has another syntax that takes an event map:
$(document).on({
mouseenter: function () {
mouse_is_inside = true;
},
mouseleave: function () {
mouse_is_inside = false;
}
}, '.my-elements');
Check out jQuery hover which is the same as:
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
UPDATE: I just realized you need to persist the events via the on() method. In that case, you can use an event map like so:
.on({
mouseenter: function() {
console.log('enter');
},
mouseleave: function() {
console.log('bye!');
}
})
Almost all jQuery methods return objects, so you can chain them together:
$(document).on('mouseenter','.my-elements', function(){
mouse_is_inside = true;
}).on('mouseleave','.my-elements', function(){
mouse_is_inside = false;
});
You could also try:
$(".my-elements").hover(function(eIn) {
// do work for mouse over
},
function(eOut) {
// do work for mouse out
});
update and correction
realized you need more dynamic lock in which case Jonathan Lonowski's or Derek Hunziker's is perfect
For starters, you can select for your elements instead of document.
$('.my-elements').on('mouseenter', function(){
mouse_is_inside = true;
});
You could try a shortcut notation like this...
$('.my-elements').on('mouseenter mouseleave', function(){
mouse_is_inside = !mouse_is_inside;
});
This will negate the value every time the mouse goes in or out, which should keep the mouse_is_inside variable set to the right value.
$('.my-elements').on('mouseenter mouseleave', function(event){
mouse_is_inside = event.type === 'mouseenter';
});
but its generally not a good idea to have a global variable incidating a event state

Hooking events with .on() with JQUERY

I want to hook events with the .on() method. The problem is I don't know how to get the object reference of the element on which the event take place. Maybe it's a midunderstanding of how the method really works... but I hope you can help.
Here's what I want to do:
When a file is selected, I want the path to be displayed in a div
<div class="wrapper">
<input type="file" class="finput" />
<div class="fpath">No file!</div>
</div>
Here's my script
$(document).ready(function() {
$this = $(this);
$this.on("change", ".finput", {}, function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
});
Something like that but that way it doesn't work.
Like this
$(document).ready(function() {
$('.finput').on("change", function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
});
Do you need to use on()? I'm not sure what you are trying to do exactly.
$("#wrapper").on("change", ".finput", function(event){
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
I haven't tested your code, but you need to attach the on() to the wrapper.
Can you just use change()?
$('.finput').change(function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
This should help. If you want to see when a file input changes, bind the event to it
$("input[type='file']").on("change", function(e){
var path = $(this).val();
})
Try:
$(document).ready(function() {
$('body').on('change','input.finput', function() {
var path = $(this).val()
$(this).parent().children(".fpath").html(path.split("\\").pop());
});
});
$(document).on("change", ".finput", function() {
$(".fpath").html(this.value.split("\\").pop());
});
This is a delegated event handler, meaning the .finput element has been inserted dynamically so we need to delegate the listening to a parent element.
If the .finput element is not inserted with Ajax and is present on page load, you should use something like this instead:
$(".finput").on("change", function() {
$(".fpath").html(this.value.split("\\").pop());
});

Categories