I've created a function which loads content and writes into html. For some reason the function is displayed after two clicks instead of one. Any idea how to make it so it load and display the info with just one click?
function getFuncDoc(funcName, targetDivId) {
var webServiceCall = funcName;
$.ajax({
type: "get",
url: webServiceCall,
success: function(doc) {
$('#' + targetDivId).load(doc, function(){
$('#' + targetDivId).toggle(
function() {
$('#' + targetDivId).css('padding', '10px');
$('#' + targetDivId).html(doc);
});
});
},
error: function(request, status, error) {
return 'Error';
}
});
}
Check if the targeted element (targetDivId) has display:none before the toggle() is triggered.
If that's not the case, then you'll need to add this attribute to your element in CSS.
toggle()-ing an element with display:block or display:inline or display:inline-block will hide the element and set its attribute to display:none, hence why you need to trigger it twice for the content to be shown.
Here is a live demo.
Related
I made an image previewer that gives a popup of an image when you hover on that link. It works but sometimes it will fail to .empty the div when I stop hovering over the link. I will ocassionally get the previous image, the error text, or two images. If I hover again it is fixed. This happens maybe 10% of the time. Also I can't get the height of the div. I don't know if this is also related.
$('<div/>',{
'id' : 'popup'
}).appendTo('body');
function showError() {
$('<div/>').text('Picture Not Found').appendTo('#popup');
$('#popup').show();
};
function getImage() {
$.ajax({
type: 'GET',
url: link,
error: function(){
showError();
},
success: function(data) {
var styleText = $('style', data).text();
var imageRegex = /background-image: url\('[^']+/;
var imageMatch = styleText.match(imageRegex);
if (imageMatch) {
var image = imageMatch[0].replace(/background-image: url\('/, '');
$('#popup').append('<img src="' + image + '" style="padding:0px" alt="">');
} else {
showError();
};
}
});
};
$('a').filter(function() {
return /users\/\d+\/pictures/.test(this.href);
}).removeAttr('title').hover(function(e) {
link = this.href.replace('http://', 'https://');
getImage();
$('#popup').show();
height = $('#popup').outerHeight();
console.log(height);
}, function() {
$('#popup').empty().hide();
})
});
Looks like it was an issue with triggering a hover event when passing over the link quickly. Seems to be fixed by adding a delay to the hover.
Here is a link to a guide that helped.
http://jelaniharris.com/2008/adding-a-delay-to-jquery-functions/
I also changed it to a separate div for the error message so I could just change the src of the image rather than empty the div. I think that makes it a little faster.
So I have a jquery click function assigned to an on/off toggle. Very simple script:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
$this.find('.slider').toggleClass('active');
});
We have two versions of this toggle. One toggles instantly when clicked and then we submit the value when clicking next(aka submit).
Our other one calls a jquery ajax function that toggles on success and upon success if it is a specific message code that is defined on the backend.
jQuery.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: {'requestType': requestType},
success: function(message) {
if(message.STATUS=='2000'){
if(currentButtonClicked=='dashboardChargingButton'){
if($('#dashboardChargingButton').html()==startCharge)
$('#dashboardChargingButton').html(stopCharge);
else
$('#dashboardChargingButton').html(startCharge);
}
if(currentButtonClicked=='invokeChargingButton'){
$( "#invokeChargingButton .slider" ).toggleClass( 'active');
}
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + " - " + xhr.statusText);
}
});
}
As you can see I have to toggle the class again using the same code but with direct targeting.
The on off toggles of this type have an onclick inside the actual html calling the function that handles this ajax.
My goal is to have my first set of code the one that targets the element and toggles the class to do all of this, but dynamically to where we don't have to call a function everytime.
Conceptually what I thought is:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
if (!$this.attr('onclick')) {
$this.find('.slider').toggleClass('active');
} else {
var clickFunction = $this.attr('onclick');
call the clickFunction
if (clickfunction = true) {
$this.find('.slider').toggleClass('active');
}
}
});
What this would do is grab the onclick, but not call it until I specify. And inside the ajax request instead of toggling I would just return true.
This might not be the best method. I am just trying to ecapsulate everything to limit the amount of code as well as make all the dom changes for those elements in one spot for any potential defects.
Here is a link to a basic fiddle of the on/off toggle.
Fiddle
I hope I explained everything in good enough detail.
I know that jQuery has a tooltip object, but I wanted to get a few things straight making my own for launching into using something that I didn't fully understand. I want the content to be displayed dynamically, but first I tried my hand using:
css: .hiddenEl{display:none;}
$(document).ready(function () {
$('#showElement').click(function () {
getText()
});
function getText() {
$.ajax({
//...ajax options
success: function (data) {
//if I use this line of code when a div with
// class hiddenEl is already on the page, it works
$('.hiddenEl').text(data.d).fadeToggle();
//when I create the div dynamically it fades in
//,and immediately fades back out.
//var $div = $('<div>').addClass('.hiddenEl').text(data.d).appendTo('body').fadeToggle();
},
error: function (xhr) {
console.log('failed: ' + xhr.status);
}
});
}
});
I'd like to know why in the version where I'm filling the div with dynamic content that it fades back out once the animation is done and in the first one it works as expected (which means the div is hidden on the second click) and how I can fix it. Secondly, I'd like to see how my version compares to someone else's who might write their own custom tooltip
EDIT: here's a non-AJAX way that's doing the same thing.
$(document).ready(function () {
$('#showElement').click(function () {
getText()
});
var array = ['first', 'second', 'third'];
function getText() {
$.ajax({
success: function (data) {
console.log('success');
//if I use this line of code when a div with
// class hiddenEl is already on the page, it works
// $('.hiddenEl').text(data.d).fadeToggle();
//when I create the div dynamically it fades in
//,and immediately fades back out.
var $div = $('<div>').addClass('.hiddenEl').text(array).appendTo('body').fadeToggle();
},
error: function (xhr) {
console.log('failed: ' + xhr.status);
}
});
}
});
I am creating an image dynamically in Jquery and trying to add a control to it When the user clicks the image, I want to popup alert() with the image's id. But I couldnt succeed to show id of the image in the alert box. Please help me display the id of the image in alert box.
here is the code display the alert box
function category_follow(search_txt) {
alert(this.Attr('name'));
}
here is the code where I create the image dynamically
$.ajax({
url: 'HoverCard_WebService.aspx?q=' + encodeURIComponent(span_text),
type: 'GET',
dataType: 'json',
beforeSend: function () {
$(".hovercard").prepend('<p class="loading-text">Yükleniyor...</p>');
},
success: function (data) {
$(".hovercard").empty();
$.each(data, function (index, value) {
var search_txt = 'TestArif4';
result += '<div><button class=\'takibe_al\' name=\'test_name\' id=\'btn_test_id\' onClick=category_follow(\'' + value.id + '\')><img id=\'img_category_follow\' src=\'images/hover_card_plus_icon.png\' class=\'hover_cursor_hand\' /></button></div>';
});
},
What are you doing with your "result" variable?
function category_follow(search_txt) {
alert(this.Attr('name'));
}
this refers to the DOM Element and "Attr" should probably be "attr" if you are using jQuery.
I recommend you to use jQuery to bind your events instead of using the element attribute onClick;
$(document).on('click', '.takibe_al', function(event) {
var $this = $(this);
alert('Clicked on element with name = ' + $this.attr('name'));
});
See on.
I want to be able to change the css of a div after I have clicked span.submit-comment.
How would I go about to change the css of that div.
I tried putting the following in the success part of the script:
$('div.news-comment:first').css("background-color", "#000");
But the div just flashes black (as I click) because it's inside the click function. I want the css to persist untill I refresh the page.
Any ideas?
// post news comment
$('span.submit-comment').live('click', function() {
var commentname = $('input#commentname').val();
var commentcontent = $('textarea#commentcontent').val();
var newsid = $('span.view-comments').attr('id');
var datastring = 'commentname=' + commentname + '&commentcontent=' + commentcontent + '&newsid=' + newsid;
$.ajax({
type: "POST",
url: "ajax/post_news_comment.php",
data: datastring,
success: function(){
$('div#news-comments').load('ajax/get_news_comments.php?news_id=' + newsid);
}
});
});
If the comment you are changing the background on is in the #news-comments div you are replacing it with the loaded html from get_news_comments.php in your .ajax callback. No matter where you put your js the element will be replaced.
If so, adding it in a callback for the load in your success function should be ok.
Your css script is ok, but just place it after load function.
Just add a return false at the end of the function for the button click, or pass in the value e and put e.preventDefault(); at the begining or end of the function.
e.g.
$('span.submit-comment').live('click', function(e) {
e.preventDefault();
// your other code.
return false;
});