I am having trouble selecting a div with jQuery after assigning the id to a Javascript variable:
$(function() {
$(".do").live("click",function()
{
var id = $(this).attr("id");
$.ajax({
//reload div using js var id
$('id').fadeOut('fast').load('http://example.com/get.php').fadeIn("slow");
});
return false;
});
});
When I call a static div it works just fine like this:
$('#staticdiv').fadeOut('fast').load('http://example.com/get.php').fadeIn("slow");
How can I select a div from a Javascript variable containing its id?
*EDIT
Here is an example if the divs:
Button to engage reload
click to reload
DIV to reload:
<div id="12">to be refreshed</div>
keep in mind the "12" us dynamic and could be any variable.
You can do that using this:
$("#"+id).fadeOut() // ...
However, I wouldn't recommend doing it that way (it won't work on things without IDs); try this instead (which should work on things without IDs):
$(".do").live("click", function() {
var me = $(this);
$.ajax({
// ...
success: function(data) {
me.fadeOut('fast').load('http://example.com/get.php').fadeIn("slow");
}
// ...
});
return false;
});
Additionally, I'm not sure if you really want that .fadeOut().load().fadeIn() chain; the load will not wait for the fadeOut to finish and the fadeIn will not wait for the load to finish (although the fadeIn will wait for the fadeOut to finish). If you have problems with that, you should try this:
me.fadeOut('fast', function() {
me.load('http://www.example.com/get.php', function() {
me.fadeIn('slow');
});
});
Aren't you supposed to use the variable id instead of string 'id'.
As follows:
$('#'+id).fadeOut('fast').load('http://example.com/get.php').fadeIn("slow");
Related
I have a snippet in my project similar to the one seen below:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$('#this_container').fadeIn();
}
});
The above snippet is working. When thisCondition evaluates to true, the container does fade in. However, I also have the snippet below that is not functioning as expected. It binds to show so that when the container fades in an event will be triggered:
$('#this_container').bind('show', function() {
$.ajax({
...
});
});
Shouldn't the snippet above react to line 5 in the change event handler? Why is the bind method not triggering?
Confirmed that show is not a valid nor jQuery-triggered event.
But you can trigger it yourself!
Try something like this :
$('#this_container').fadeIn("slow", function() {
$(this).trigger("show");
});
The show is not a valid event, neither is triggered by jQuery. You need to construct your script in a different way altogether:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$.ajax({
success: function () {
$('#this_container').fadeIn();
}
});
}
});
So, you can try to bring the AJAX content, and upon a successful request, you can show the container.
try to use :
$('#this_container').fadeIn( "slow", function() {
// Animation complete
$.ajax({
...
});
});
Im trying to code a site where the objective is to click on two identical images and it hides the both the images you've managed to match to eachother.
$(document).ready(function(){
var animal1;
var animal2;
$(".memory1").on("click", function(){
animal1 = $(this).data('animal');
});
$(".memory2").on("click", function(){
animal2 = $(this).data('animal');
if (animal1==animal2){
$(this).data('animal').hide();
}
else {
alert("Wrong, Try again!");
}
});
});
so the line where its going wrong is obviously
$(this).data('animal').hide();
But I cant figure out a way to hide both images, or a better way of going about it.. :/
http://jsfiddle.net/4vgfca76/
This doesn't work the way you think it does
$(this).data('animal').hide();
When data is used with one argument, it get's the data attribute, which you should already know as you're doing it a few lines above.
What you get is the string hund etc. and that string doesn't have a hide() method.
You should be using the attributes selector to select the elements with that attribute instead
$(document).ready(function () {
var animal1, animal2;
$(".memory1").on("click", function () {
animal1 = $(this).data('animal');
});
$(".memory2").on("click", function () {
animal2 = $(this).data('animal');
if (animal1 == animal2) {
$('img[data-animal="'+animal1+'"]').hide();
} else {
alert("Fel! Försök igen");
}
});
});
I'm trying to create a simple click catcher where if you click .image-class the javascript will take the href from another element with a class name of .btn and send you to it's destination. Though I keep getting errors on lines 7 & 10 saying that undefined is not a function. How do I make this work?
<script>
var ClickCatcher=
{
init:function(){
var link = jQuery('.btn')[1].href;
var imgCatch = jQuery('.image-class');
imgCatch.addEventListener("click", ClickCatcher.clickListener, false);
},
clickListener:function(){
window.location = link;
}
};
ClickCatcher.init();
</script>
You can do this with jquery with a simple click event
jQuery('.image-class').on('click', function (){
window.location = jQuery('.btn').eq(1).attr('href');
});
But if you still want to write in the way you have you can do:
var ClickCatcher = {
init: function () {
jQuery('.image-class').on('click', function (){
window.location = jQuery('.btn').eq(1).attr('href');
});
}
};
ClickCatcher.init();
Just make sure to fire the init method after dom load.
update: One issue with it is that you have coded your target etc in the code rather then pass it, so its going to be hard to reuse, you'd be better off doing:
var ClickCatcher = {
init: function ($button, loc) {
$button.on('click', function (){
window.location = loc;
});
}
};
ClickCatcher.init(jQuery('.image-class'), jQuery('.btn').eq(1).attr('href'));
That way the internal working is seperate from the dom (as you are passing the dom dependencies to the function.
#atmd showed a very good way of doing this. If you just want to know what your mistake was though. It is wa an error in your jQuery stament to get the btn href
jQuery('.btn')[1].href
you need to call the attr function and then get the href attr. and use .eq(1) to reduce the set to the first btn
jQuery('.btn').eq(1).attr('href);
I'm using object literals on my project. I'm targeting selecting with jquery. It works fine the first time but when the part I'm targeting is reloaded with AJAX I can't target those element anymore. But I look into firebug they're there...
I'm even doing console.log() to test if my code works and it works but it just doesn't want to pick those. So in order for it to work, I have to refresh the entire browser.
Do you know what's the deal with AJAX dom reload and selectors.
I think it's something to do with the DOM reloading and redrawing itself or something along those lines...
Here is my code:
Module.editWishlistTitle = {
wishListContent: $('.mod-wish-list-content'),
title: $('.title').find('h2'),
titleTextField: $('#wishlist-title-field'),
titleInnerContainer: $('.title-inner'),
editTitleForm: $('.edit-title-form'),
submitCancelContainer: $('.submit-cancel'),
notIE9: $.browser.msie && $.browser.version < 9,
edit: function () {
var fieldTxt = this.titleTextField.val(),
editForm = this.editTitleForm,
titleParent = this.titleInnerContainer,
fieldCurrentTitle = this.title.text();
this.titleTextField.val(fieldCurrentTitle);
this.submitCancelContainer.removeClass('hidden');
if (!this.notIE9) {
editForm.css('opacity', 0).animate({ opacity: 1 }).removeClass('hidden');
titleParent.addClass('hidden').animate({ opacity: 0 });
console.log(editForm);
} else {
editForm.removeClass('hidden');
titleParent.addClass('hidden');
}
}
init: function () {
var self = this;
console.log(this.editTitleForm);
//edit
this.wishListContent.delegate('.edit-title a', 'click', function (e) {
self.edit();
e.preventDefault();
});
};
If you are replacing an element on the page, you are destroying the original reference to the element. You need to redo the reference to point to the new element.
Create a new method in your code that (re)initializes the references you need. Instead of adding them in the odject, set them in the method.
Basic idea:
Module.editWishlistTitle = {
wishListContent: $('.mod-wish-list-content'),
title: $('.title').find('h2'),
//titleTextField: $('#wishlist-title-field'),
...
...
initReferences : function(){
this.titleTextField = $('#wishlist-title-field');
},
...
...
init: function () {
this.initReferences();
...
...
And when your Ajax call comes back you just need to call initReferences again.
After DOM ready, if you inject any data / class / id will not be available in DOM, so better you use live or delegate to get your new data access.
http://api.jquery.com/delegate/
Best to use delegate, that will take care your new data loaded after dom ready, that way you can avoid to refresh /reload your page.
In my html page, I have a select with some options.
When selecting an option, an ajax call is fired passing the option's value to a php script, which returns an html fragment (another select) with a certain id that is appended to the page.
When the user selects another option from the first select, the event is fired again, the ajax call is executed and another html fragment (with the same id) gets appended to the page.
I want that, if the event is fired a second time, the appended element is removed form the page before appending the new one.
At the moment I'm using this code:
$(document).ready(function() {
$("#id_serie").change(function() { //#id_serie is the if of the first select
if ($("#id_subserie_label")) { //#id_subserie_label is the id of the html element returned by the ajax call
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
This is not working though, the html element returned by the second ajax call is appended after the element returned from the first call (because the element with id #id_subserie_label is not in the page when the script is loaded?).
How can I achieve what I need?
You're very close.
Just change if ($("#id_subserie_label")) to if ($("#id_subserie_label").length):
$(document).ready(function() {
$("#id_serie").change(function() {
if ($("#id_subserie_label").length) { // <=== change this line
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
See The jQuery FAQ: How do I test whether an element exists?.
This is because, as Ivo points out:
$("#id_subserie_label") is an object, and objects always evaluate to true.
As per Andy E's comment, you can simplify your code to this, if you don't need the console.log() call:
$(document).ready(function() {
$("#id_serie").change(function() {
$("#id_subserie_label").empty().remove();
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});