I have a text input field, on which when you click a json request fires off, and some data gets retrieved.
$("input").focus(function(){
var thefield = $(this);
$.getJSON("http://www.blabla.com/bla",
function(data){
alert(JSON.stringify(data));
thefield.val('blabla');
}
);
});
How can I do so this request only gets to run once and not every time I focus on the text field? But I still want data to be available when I focus the 2nd, 3rd time etc.
$('input').one('focus', function() {
// load data using ajax
$(this).data('ajax-data', data);
});
$('input').focus(function() { $(this).val($(this).data('ajax-data')); });
Assign another function on the first click or store some value in alt attribute indicating whether you need to fire a request or not
Something like this will do the trick:
//have this line outside any function to make it global:
var _globalData = "";
$("input").focus(function(){
if ($(this).attr("focused") == "1") {
alert("already focused before, data is: " + _globalData);
}
else {
var thefield = $(this);
$.getJSON("http://www.blabla.com/bla",
function(data) {
_globalData = JSON.stringify(data);
alert(_globalData);
thefield.val('blabla');
thefield.attr('focused', '1');
});
}
);
If your input elements do not share the same data do this:
function loadData(field) {
$.getJSON("http://www.blabla.com/bla",
function(response){
field.data("ajax-data", response).val(response);
}
);
};
$("input").focus(function(){
var $this = $(this);
if ($this.data("ajax-data")) {
$(this).val($this.data("ajax-data"));
} else {
loadData($this);
}
});
If they do share data, it's nearly the same code but with a shared variable instead of using data.
var data = null;
function loadData(field) {
$.getJSON("http://www.blabla.com/bla",
function(response){
data = response;
field.val(response);
}
);
};
$("input").focus(function(){
var $this = $(this);
if (data) {
$(this).val(data);
} else {
loadData($this);
}
});
You can also create a small jQuery plugin to handle any of the above scenarios, and that also support multiple events:
(function($){
$.fn.loadInputData = function(options){
var defaults = {
url: "http://www.blabla.com/bla",
events: "focus",
sharedData: false
};
var _data = null;
options = $.extend({}, defaults, options);
function loadData(field){
$.getJSON(options.url,
function(response){
if (options.sharedData) {
_data = response;
} else {
field.data("ajax-data", response);
}
field.val(response);
}
);
}
return this.each(function(){
var $this = $(this);
$this.bind(options.events, function(){
if ((options.sharedData && !_data) ||
(!options.sharedData && !$this.data("ajax-data")) {
loadData($this);
} else {
$this.val(options.sharedData ? _data : $this.data("ajax-data"));
}
});
})
};
})(jQuery);
Usage for this plugin would be:
$("input").loadInputData({ sharedData: true });
And just for the kicks, an improved version of the accepted answer:
$('input').one('focus', function() {
var $this = $(this);
$.getJSON("http://www.blabla.com/bla",
function(response){
$this.data("ajax-data", response).val(response);
}
);
$this.focus(function() { $this.val($this.data('ajax-data')); });
});
Related
here is my javascript Accordion code,i use multi-label accordion . first label work but does not work 2nd or 3rd label ,when i click first label accordion it does not expand .I bring in the content for the accordion dynamically using AJAX . mainly i wont show data dynamically when insert or update any data from admin panel by using setTimeInterval.
<script type="text/javascript">
var multisidetabs=(function(){
var opt,parentid,
vars={
listsub:'.list-sub',
showclass:'mg-show'
},
test=function(){
console.log(parentid);
},
events = function(){
$(parentid).find('a').on('click',function(ev){
ev.preventDefault();
var atag = $(this), childsub = atag.next(vars.listsub);
//console.log(atag.text());
if(childsub && opt.multipletab == true){
if(childsub.hasClass(vars.showclass)){
childsub.removeClass(vars.showclass).slideUp(500);
}else{
childsub.addClass(vars.showclass).slideDown(500);
}
}
if(childsub && opt.multipletab == false){
childsub.siblings(vars.listsub).removeClass(vars.showclass).slideUp(500);
if(childsub.hasClass(vars.showclass)){
childsub.removeClass(vars.showclass).slideUp(500);
}else{
childsub.addClass(vars.showclass).slideDown(500);
}
}
});
},
init=function(options){//initials
if(options){
opt = options;
parentid = '#'+options.id;
//test();
events();
}else{ alert('no options'); }
}
return {init:init};
})();
multisidetabs.init({
"id":"mg-multisidetabs",
"multipletab":false
});
// set time
function loadDoc() {
$.ajax({
url: "indexLoad.php",
success: function (data) {
v=data;
$("#demo").html(data);
}
});
return v;
}
setInterval(function () {
loadDoc();
}, 100);
"
I'm trying to include this snippet of code:
;(function($) {
'use strict'
var ajaxContactForm = function() {
// http://www.bitrepository.com/a-simple-ajax-contact-form-with-php-validation.html
$('.contact-form').each(function() {
var $this = $(this);
$this.submit(function() {
var str = $this.serialize();
$.ajax({
type: "POST",
url: $this.attr('action'),
data: str,
success: function(msg) {
// Message Sent? Show the 'Thank You' message and hide the form
var result;
if(msg == 'OK') {
result = '<div class="notification_ok">Thank you! Your message has been sent!</div>';
} else {
result = msg;
}
result = '<div class="result">' + result + '</div>';
$this.find('.note').html(result);
}
});
return false;
}); // submit
}); // each contactform
}; // contact
// Dom Ready
$(function() {
ajaxContactForm();
// Initialize responsive menu
ResponsiveMenu.initial($(window).width());
$(window).resize(function() {
ResponsiveMenu.menuWidthDetect($(this).width());
});
// Detect elements into viewport
$('[data-waypoint-active="yes"]').waypoint(function() {
$(this).trigger('on-appear');
}, { offset: '90%' });
$(window).on('load', function() {
setTimeout(function() {
$.waypoints('refresh');
}, 100);
});
});
})(jQuery);
Into this file:
http://rocketgram.co/js/custom.js
However whenever I try and merge the two correctly (Or what I thought) I can only get one or the other working at once. Not both. Can anyone share any light on why these are conflicting?
Here's a few reference links on both of them working, singularly:
rocketgram.co/mainjs.html
rocketgram.co/customjs.html
And here's the file in the snipped above:
rocketgram.co/js/main.js
I have using ViewItems() function in An-click='VewItems(id)' to call a method in Controller in Angularjs but it seem not good yet because when user click more time my images which load from Model it will get more image or element which I append to a div much as the amount of clicking.
Here is my Function
$scope.ViewItems = function ($id) {
$('.modal-title').html('');
$('#bookimg').html('');
// Fetch an item from book list
if($id) {
id = $id;
$http({
method: 'GET',
url: url+id,
}).then(function successCallback(response) {
var http_code = response.data.s_respond;
$('<div id="loading"></div>').appendTo('body');
if (http_code === 200) {
SetErrors(http_code, 'OK');
var book_items = JSON.parse(response.data.data);
$('<h3>'+book_items.title+'</h3>').appendTo('.modal-title');
$('<img src=" '+book_items.image+' " width="100%" />').appendTo('#bookimg');
$('#myModal').modal({backdrop: 'static', keyboard: false});
} else {
SetErrors(http_code, 'warning');
}
}, function errorCallback(response) {
SetErrors(http_code, response.textStatus);
});
}
};
HTML
Maintain a variable isClicked and handle the callback accordingly.
var isClicked = false;
$scope.ViewItems = function ($id) {
if (isClicked) {
return;
}
isClicked = !isClicked;
...
}
Just create an array to solve this
var loadedIds = [];
$scope.ViewItems = function ($id) {
var index = loadedIds.indexOf($id);
if(index == -1){
loadedIds.push($id);
-------
}
};
I have 2 javascripts that are conflicting with eachother, the newer one (Zeroclipboard) conflicts with the older one (delete row) and won't let the delete row one work. The moment i removed the zeroclipboard one, delete worked.
Tried adding jQuery.noConflict(); but didn't seem to work. By reading few solutions, I decided to remove $ signs, but still no.
I have a files.php file, including the header.php file. I am adding the custom.js file in header.php, which holds many functions for operations across the project, including the delete row function. Whereas, the newer script for ZerClipboard is in files.php itself.
Older one, to delete a table row on delete icon click, which won't work after I add the next:
custom.js
function deleteRow()
{
var current = window.event.srcElement;
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
$(document).ready(function()
{
$('table#delTable td a.delete').click(function()
{
if (confirm("Are you sure you want to delete?"))
{
var fid = $(this).parent().parent().attr('fid');
var str=$(this).attr('rel');
var data = 'fid=' + $(this).attr('rel') + '&uid=' + $(this).parent().attr('rel');
var deletethis = '#tr' + $(this).attr('rel');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "delete.php",
data: data,
cache: false,
success: function(msg)
{
$(deletethis).fadeOut('slow', function() {$(this).remove();});
}
});
}
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
ZeroClipboard's JS and SWF, along with this js to copy some text on clipboard on Share icon click:
files.php
<script type="text/javascript" src="js/ZeroClipboard.js"></script>
<script language="JavaScript">
var clip = null;
function $(id) { return document.getElementById(id); }
function init()
{
clip = new ZeroClipboard.Client();
clip.setHandCursor( true );
}
function move_swf(ee)
{
copything = document.getElementById(ee.id+"_text").value;
clip.setText(copything);
if (clip.div)
{
clip.receiveEvent('mouseout', null);
clip.reposition(ee.id); }
else{ clip.glue(ee.id); }
clip.receiveEvent('mouseover', null);
}
</script>
I used this blog post for implementing multiple zerclipboard - http://blog.aajit.com/easy-multiple-copy-to-clipboard-by-zeroclipboard/
And, here's the HTML source generated by the files.php page - http://jpst.it/tlGU
Remove the follow function definition of your second script:
function $(id) { return document.getElementById(id); }
Because this is redefining your $ object in window context, due when you use $ in your first script you're not using jquery, instead you're using your new function definition.
Hope this helps,
Here is how you should use noConflict() :
function deleteRow()
{
var current = window.event.srcElement;
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
jQuery.noConflict(); // Reinitiating $ to its previous state
jQuery(document).ready(function($) // "Protected" jQuery code : $ is referencing jQuery inside this function, but not necessarily outside
{
$('table#delTable td a.delete').click(function()
{
if (confirm("Are you sure you want to delete?"))
{
var fid = $(this).parent().parent().attr('fid');
var str=$(this).attr('rel');
var data = 'fid=' + $(this).attr('rel') + '&uid=' + $(this).parent().attr('rel');
var deletethis = '#tr' + $(this).attr('rel');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "delete.php",
data: data,
cache: false,
success: function(msg)
{
$(deletethis).fadeOut('slow', function() {$(this).remove();});
}
});
}
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
And in files.php:
<script src="js/ZeroClipboard.js"></script>
<script>
var clip = null;
function $(id) {
return document.getElementById(id);
}
function init() {
clip = new ZeroClipboard.Client();
clip.setHandCursor(true);
}
function move_swf(ee) {
copything = document.getElementById(ee.id + "_text").value;
clip.setText(copything);
if (clip.div) {
clip.receiveEvent('mouseout', null);
clip.reposition(ee.id);
} else {
clip.glue(ee.id);
}
clip.receiveEvent('mouseover', null);
}
</script>
I recently deployed an infinite scroll to an app that I have build and found that sometimes I need to click twice for something to happen.
My app has likes, and once the dom had loaded, i need to click on the like button twice before it changes, then once i click on the other ones it's okay but I always have to click once for the app to almost "wake up"
Is there a better solution?
$(document).ready(function() {
function runUpdate(url, item) {
$.ajax({
type: "GET",
url: url,
cache: false,
success: function(data){
if (data == '200') {
removeAddColor(item);
}
}
});
}
$('.mini-like').live('click', function(){
$('.mini-like').toggle(
function() {
var item = $(this);
var href = item.attr('href');
runUpdate(href, item);
},
function() {
var item = $(this);
var rel = item.attr('rel');
runUpdate(rel, item);
}
);
});
function removeAddColorFollow(item) {
var href = $(this).attr('href');
var rel = $(this).attr('rel');
if (item.hasClass('btn-success')) {
$(item).removeClass('btn-success').attr('href', href).attr('rel', rel);
$(item).find('i').removeClass('icon-white');
} else {
$(item).addClass('btn-success').attr('href', rel).attr('rel', href);
$(item).find('i').addClass('icon-white');
};
}
});
Well unless I'm completely wrong, you only attach the toggle event to .mini-like after it has been clicked once. Try to just replace
$('.mini-like').live('click', function() {...
With
$(function() {...
To attach the toggle event handler on document ready instead of on click
The code $('.mini-like').live('click',... should be placed inside $(document).ready()
You can use .on in place of .live. As .on is a new method and .live is deprecated now you should use .on
UPDATE
The re-written version will be
$(document).ready(function(){
$('.mini-like').on('click', function(){
$('.mini-like').toggle(
function() {
var item = $(this);
var href = item.attr('href');
runUpdate(href, item);
},
function() {
var item = $(this);
var rel = item.attr('rel');
runUpdate(rel, item);
}
);
});
});
function runUpdate(url, item) {
$.ajax({
type: "GET",
url: url,
cache: false,
success: function(data){
if (data == '200') {
removeAddColor(item);
}
}
});
}
function removeAddColorFollow(item) {
var href = $(this).attr('href');
var rel = $(this).attr('rel');
if (item.hasClass('btn-success')) {
$(item).removeClass('btn-success').attr('href', href).attr('rel', rel);
$(item).find('i').removeClass('icon-white');
} else {
$(item).addClass('btn-success').attr('href', rel).attr('rel', href);
$(item).find('i').addClass('icon-white');
};
}