jquery class selector yields unusable id - javascript

I am getting an id that is not addressable by jquery ("#"+id).something .
At document start I have a :
var g_justClicked = '';
$.ajaxSetup({
beforeSend:function(event){
if(g_justClicked) {
console.log('g_justClicked='+g_justClicked+' tagName='+$('#'+g_justClicked).tagName);
};
var wOffset = $('#'+g_justClicked).offset();
$('#loading').show();
},
complete:function(){
$('#loading').hide();
}
});
At document end I have another script (all elements with class spinner should set the global variable 'g_justClicked'):
$(document).ready(function () {
$('.spinner').click(function() {
g_justClicked = $(this).attr('id');
console.log('.spinner.click: g_justClicked='+g_justClicked);
});
This works fine, the variable is set and displayed correctly in ajaxSetup.
BUT: referencing it in tagName= or in wOffset = with
$('#'+g_justClicked).
results in
"TypeError: wOffset/tagName is undefined"
Note: all ids start with several characters, t.e. "boxshow12345" is a typical id.
What am I doing wrong?

I think was able to reproduce your scenario here: https://jsfiddle.net/mrlew/qvvnjjxn/3/
The undefined in your console.log is because you're accessing an inexistent jQuery property: .tagName. This property is only available to native HTML Element.
To retrieve the tag name from a jQuery Object, you should use: .prop("tagName"), or access the property accessing the native element with $('#'+g_justClicked)[0].tagName
So, if you change
console.log('g_justClicked='+g_justClicked+' tagName='+$('#'+g_justClicked).tagName);
to:
console.log('g_justClicked='+g_justClicked+' tagName='+$('#'+g_justClicked).prop("tagName"));
Will successfully log: g_justClicked=boxshow12345 tagName=BUTTON, as expected.
Note: In order to your logic work, you have to click .spinner first.

Your problem is that your ajax setup runs regardless of whatever you do in the click handler, and it runs before you even setup that handler. The initial value for g_justClicked is empty string, and this is what it tries to access in $('#'+g_justClicked), hence the error.
If you want to click the spinner and then pass the id to the beforeSend, do it like this:
$(document).ready(function() {
$('.spinner').click(function() {
var g_justClicked = this.id; //simplify this a bit
console.log('.spinner.click: g_justClicked=' + g_justClicked);
// call ajax
_setupAjax( g_justClicked );
});
});
function _setupAjax(g_justClicked) {
$.ajaxSetup({
beforeSend: function(event) {
if (g_justClicked) {
console.log('g_justClicked=' + g_justClicked + ' tagName=' + $('#' + g_justClicked).tagName);
};
var wOffset = $('#' + g_justClicked).offset();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
}
UPDATE
If you don't want a separate function, just move your ajax setup into the click handler:
$(document).ready(function() {
$('.spinner').click(function() {
var g_justClicked = this.id; //simplify this a bit
console.log('.spinner.click: g_justClicked=' + g_justClicked);
// call ajax setup
$.ajaxSetup({
beforeSend: function(event) {
if (g_justClicked) {
console.log('g_justClicked=' + g_justClicked + ' tagName=' + $('#' + g_justClicked).tagName);
};
var wOffset = $('#' + g_justClicked).offset();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
});
});

OK #mrlew.
Answer: I tried your .prop appoach, but still got "undefined". Now back to the roots:
The goal is to get the id of any element that was clicked to modify the busy indicators position, while ajax is running. Newly I am back to my original approach, without global variable and parameter passing:
$(document).ready(function () {
$('.spinner').click(function() {
_setupAjax();
});
});
which works, and:
function _setupAjax() {
$.ajaxSetup({
beforeSend: function() {
$('#loading').show();
wJustClicked = $(this).attr('id'); /// <- that doesnt work!
console.log("_setupAjax wJustClicked="+wJustClicked);
console.log('_setupAjax tagName=' + $('#' + wJustClicked).prop("tagName"));
....defining css based on id (no problem)..
which yields "undefined" twice. I tried so many ways to get that f.... id.

#mrlew
thanks a lot for your help. Meanwhile I found the solution. All trouble came from a timing problem. Here is what works (for all DIV, SPAN and IMG of class=spinner and having an id:
$(document).ready(function () {
_setupAjax();
$('.spinner').click(function() {
wJustClicked = $(this).attr('id');
if(wJustClicked == null) alert('Id missing on item clicked');
console.log('.spinner.click! id='+wJustClicked);
var wOffset = $('#' + wJustClicked).offset();
var xPos = Math.round(wOffset.left) + 8;
var yPos = Math.round(wOffset.top) + 4;
console.log(wJustClicked+' offset left='+wOffset.left+' top='+wOffset.top+' xPos='+xPos+' yPos='+yPos);
wDiv = 'loading';
$('#'+wDiv).css('left',xPos);
$('#'+wDiv).css('top',yPos);
});
and the js function:
function _setupAjax() {
$.ajaxSetup({
beforeSend: function() {
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
}
A strange thing remained (I have firebug installed), which I have solved with Math.round: the x and y position come overdetailed like 170.5134577 and 434.8768664 ?!?
I can live with that. But where does this pseudo precision come from?
Again thanks a lot to keep my hope upright.

Related

Ajax Loader showing twice in function

I have created a fiddle here...https://jsfiddle.net/qukhn4uk/
As you can see, I have an object for clicking on a grid image that opens a flyout and loads that person's data through ajax (you won't see the data load in the fiddle obviously but you get the idea). Everything works good here. The object that handles this is:
Stories = {
flyout: '#flyout',
closeFlyout: '#flyout .close-flyout',
storyTrigger: '.story .story-trigger',
ajaxContentContainer: '#flyout .content',
loader: '<i class="fa fa-spin fa-spinner"></i>',
body: 'body',
init: function() {
$(this.storyTrigger).click(this.showStory.bind(this));
$.ajaxSetup({cache:false});
$(document).on("click", this.closeFlyout, this.closeStory.bind(this));
},
showStory: function(e) {
e.preventDefault();
var target = $(e.target),
targetName = target.data("name");
$(this.flyout).css("transform", "translateX(-100%)");
$(this.body).css("overflow", "hidden");
$(this.ajaxContentContainer).append(this.loader);
$(this.ajaxContentContainer).load("/story/" + targetName);
},
closeStory: function() {
$(this.flyout).css("transform", "translateX(100%)");
$(this.ajaxContentContainer).empty();
$(this.body).css("overflow", "auto");
}
}
I then have another load function for opening the flyout and loading the data based on a hash in the url. This is the object that handles that...
DirectStory = {
storyDiv: '.story',
init: function() {
var self = this;
if ( window.location.hash != '' ) {
$(this.loadStory.bind(this));
}
$.ajaxSetup({cache:false});
},
loadStory: function() {
var hash = window.location.hash,
story = hash.substring(1);
targetStory = $(this.storyDiv).find("[data-name='" + story + "']");
targetStory.click();
}
}
Everything works great but there is one tiny glitch. For some reason, the DirectStory object is causing the ajaxLoader from the Stories object to load twice. Can someone help me figure out why this is happening? Thanks!
UPDATE: I have figured out that the targetStory.click() is running twice inside of the DirectStory object. I have tried to unbind it first but that does not help. Why is it running twice?
I have solved this for anyone who lands here...
The targetStory variable was finding two triggers with the way I was storing it.
I simply updated the targetStory variable to...
targetStory = $(".full-link[data-name='" + story + "']");

JQuery conditional preventDefault() firing when not called

I have the following script I've written.
<script>
$(document).ready(function(){
$('a').data('loop',true);
$('body').on('click', 'a', function(event){
console.log($(this).data('loop'));
if ($(this).data('loop') == 'true') {
console.log('hit');
event.preventDefault();
caller = $(this);
$(this).data('loop',false);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
$(caller).click();
}
});
} else {
console.log(event.isDefaultPrevented());
console.log('miss');
$(this).data('loop',true);
}
});
});
</script>
It works, sends me the details I want etc etc. BUT!!!
When I click a link, It fires off the details to me via Ajax, then it's meant to "click" the event again, which it does! but the event does not fire it's normal action. So When clicking a link to another page, I would go to that other page... that's not happening.
If I comment out the line event.preventDefault(); Then the event fires as I would expect...
So to me it looks like the event.preventDefault is executing even though it's not meant to be during the second call...
Sorry if this is a bit complicated to understand. I don't quite understand what's happening myself.
Is it possibly a bug, or is there something that I've done that has caused this?
I didn't think I could, but I have successfully made a jsfiddle for this.
https://jsfiddle.net/atg5m6ym/2001/
You can try this and not worry about the "loop" anymore:
$(document).ready(function () {
$('body').on('click', 'a', function (event) {
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
window.location.href = linkref; // Redirect happens here
}
});
});
});
UPDATE
There's a few issues to note here:
1) Some links don't require a redirect (as noted, bootstrap model links that control showing/hiding or within document anchors
To correct this it really depends on the case. Usually bootstrap adds specific classes or data attributes to the links so you can do something like.
$('body').on('click', 'a:not(list of things to exclude)'..
Personally I'd instead define the links I wanted to track as :
<a href=<link> data-tracked='true'...
<script>
$('body').on("click","a[data-tracked='true']"...
Or if you want to track most links with a few exceptions you can:
<a href=<link> data-tracked='false'...
<script>
$('body').on("click","a:not([data-tracked='false'])"...
Or more generally:
<script>
$('body').on("click","a", function () {
if ($(this).attr("data-tracked") == "false" || <you can check more things here>){
return true; //Click passes through
}
//Rest of the tracking code here
});
The following if statement will return true whenever the data-loop attribute exists against an element, regardless of it's value:
if ($(this).data('loop')) {
It needs to be changed to check for the value:
if ($(this).data('loop') == 'true') {
When you assign anything to be the value of an element attribute it becomes a string and, as such, requires a string comparison.
Event.preventDefault() is not being executed second time.
Link redirection happens when the method is completed.
So in your case redirection will happen when complete method of ajax call is completed.
lets say, we have event1 and event2 object in the code. event1 is the object in the ajax call method and event2 is the event object in recursive call (second call) method.
so when link is clicked second time , we still have complete method to be executed. as soon as it returns to the complete method of ajax call, it finds the event1 is having preventDefault property true and it does not redirect.
Try this ;)
$(document).ready(function(){
$('body').on('click', 'a', function(event){
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({
linkref: linkref,
linkpos: linkpos,
screenwidth: screenwidth
});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
/* To temprary block browser; */
async: false,
data: "json=" + json_data,
complete: function(jqXHR, status){
/* add class **ignore** to a element you don't want to redirect anywhere(tabs, modals, dropdowns, etc); */
if(!caller.hasClass('ignore')){
/* Redirect happens here */
window.location.href = linkref;
}
}
});
});
});

jquery unable to show and hide an element

I have div element as
<div class="preview-image hide"><img src="{{STATIC_URL}}ui-anim_basic_16x16.gif"></div>
The hide class belongs to Twitter Bootstrap 2.3.2, the preview-image basically adds some styling to the element and used as handle for JavaScript.
I have jQuery code as below where
$loading.show() and $loading.hide() are not working.
The surprising this is when I run $preview.parent().find('.preview-image').show() from console, its working!!
(function($) {
$(document).ready(function() {
var SET_TIME = 6000;
$('[data-preview]').click(function() {
var $this = $(this);
var $preview = $('#' + $this.data('presponse'));
var $loading = $preview.parent().find('.preview-image');
$loading.show();
$.ajax({
});
$loading.hide();
});
});
})(window.jQuery);
Because $.ajax() is an asynchronous call, the $loading.hide() is being called (as it appears to the user) immediately after the $loading.show(). In order to circumvent this, you should make the $loading.hide() call after your AJAX call is complete. One way to do this is:
var $loading = $preview.parent().find('.preview-image');
$loading.show();
$.ajax({
}).always(function() {
$loading.hide();
});
Is the issue that it's hiding straight away? I think the hide needs to be within a success function of the AJAX call rather than being after it.
Eg.
$.ajax({
success: function() {
$loading.hide();
}
});

jQuery change event returns null when manually fired on $(document).ready();

I'm currently writing a JQuery plugin that loads colors from a JSON web service into a drop down list.
The drop down list background-color changes according to the selected value. For the most part it is working. on any regular change it works as expected, the problem I am having is on the initial page load I am using triggerHandler("change"); and it triggers but I seem to be getting an undefined error on the selected value from the drop down list on page load so it doesn't trigger the color change on the drop down list
My code is:
$.fn.bindColorsList = function (options) {
var defColor = options.defaultColor;
var svcUrl = options.svcurl;
//var f_target = options.filterTarget;
var $this = this;
$.ajax({
url: options.svcurl,
dataType: 'json',
/*data: { filter: src_filt },*/
success: function (fonts) { fillcolors(fonts, $this) },
error: function () { appendError(f_target, "colors failed to load from server") }
});
this.on("change", function (event) {
log($(event.target).attr("id") + " change detected");
//change ddl dropdown color to reflect selected item ;
var hcolor = $this.find('option:selected').attr("name");
$this.attr("style", "background-color:" + hcolor);
});
function fillcolors(colors, target) {
$(target).empty();
$.each(colors, function (i, color) {
$(target).append("<option name='"+color.HexValue+"' value='" + color.Name + "' style='background-color:"+color.HexValue+"'>"+color.Name+"</option>");
});
};
//in a seperate file
$(document).ready(function () {
$("#dd-font-color").bindColorsList({ svcurl: "/home/colors"});
$("#dd-back-color").bindColorsList({ svcurl: "/home/colors" });
});
You are doing an AJAX request to populate your dropdown which, by the way, is an asynchronous one. In this case you need to trigger the event in the success callback of the AJAX request.
var $this = this;
// Bind the onchange event
$this.on("change", function (event) {
..
});
// Populate using AJAX
$.ajax({
...
success: function (fonts) {
// Populate the values
fillcolors(fonts, $this);
// Trigger the event
$this.trigger("change");
},
...
});
That's it.

Fadeout div after executing script with jQuery

With this function I want to submit data (res_id) to a script and fadeout the div by it's id (using variable pos), the script is executed but the div won't fade out. Why is that?
$('.remove_resort').click(function() {
pos = $(this).attr("id");
rem_res();
});
function rem_res() {
$.get("/snowreport/request/remove.php", {
res_id: pos
}, function(data1) {
pos.fadeOut("slow");
});
}
pos contains the ID string, so you need $("#" + pos).fadeOut("slow")
pos is outscoped. You should pass it as an argument to the function.
$('.remove_resort').click(function() {
pos = $(this).attr("id");
rem_res(pos);
});
function rem_res(pos) {
$.get("/snowreport/request/remove.php", {
res_id: pos
}, function(data1) {
pos.fadeOut("slow");
});
}
You're storing pos = $(this).attr("id"), which is a string, not a jQuery object. What your original code is doing is trying to call "somestring".fadeOut(), which won't work. If you keep a reference to the jQuery object for the element and call fadeOut on that, it should fade out.
Let's rewrite this code so that it does what you're after, is a little cleaner and more obvious:
$('.remove_resort').click(function() {
rem_res(this);
});
function rem_res(element) {
var $element = $(element),
id = element.id;
$.get("/snowreport/request/remove.php", { res_id: id }, function(data) {
$element.fadeOut("slow");
});
}

Categories

Resources