Javascript / Jquery file combination - javascript

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

Related

how to disable more than one times when a link was click by user in Angularjs

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);
-------
}
};

How to hide a div after complete the ajax call,my code is given below ..in this code div hide before the refresh

How to hide a div after complete the ajax call,my code is given below... in this code div hide before the refresh
$(document).ready(function() {
$('#search-button').click(function() {
$('#imgLoader').show();
var request = $.ajax({
type: "GET",
url: 'response.php',
data: $('#search-form').serialize(),
success: function(response) {
var url = 'detail_page.php';
$('#my_cart').load(url + ' #mycart');
$('#refcart').load(url + ' #shoppingCart');
$('#imgLoader').hide();
}
})
});
});
image loader hide before complete the refresh of two divs. Please help me
Take a look at http://api.jquery.com/load/
You can add a callback to the .load methods that will trigger once the element is fully loaded.
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
In your case, something like that:
$('#my_cart').load(url + ' #mycart', function () {
$('#imgLoader').hide();
);
A possible solution could be by using the complete parameter of load:
success: function(response) {
var url = 'detail_page.php';
$('#my_cart').load(url + ' #mycart', function() {
$('#refcart').load(url + ' #shoppingCart', function() {
$('#imgLoader').hide();
});
});
}
Keep in mind, thats not the best solution, because the second load will be executed not until the completion of the first.
Edit:
I would suggest you to work with tokens:
success: function(response) {
var myCartLoaded = false;
var refCartLoaded = false;
var url = 'detail_page.php';
$('#my_cart').load(url + ' #mycart', function() {
myCartLoaded = true;
if(refCartLoaded) {
$('#imgLoader').hide();
myCartLoaded = false;
refCartLoaded = false;
}
});
$('#refcart').load(url + ' #shoppingCart', function() {
refCartLoaded = true;
if(myCartLoaded) {
$('#imgLoader').hide();
myCartLoaded = false;
refCartLoaded = false;
}
});
}
This way both load-functions will start at the same time and the one which stops last will trigger to hide your imageLoader.
You have more than one error in your code :
You make an ajax request to get search result, but you don't use the
response inside the success function. $().load is async, that
means you should wait the end of each $().load request before
hiding #imgLoader
The $().load is working like this
.load( url [, data ] [, complete ] )
And you should use promises to make it work.
$(document).ready(function() {
$('#search-button').click(function() {
$('#imgLoader').show();
// create the deffered instances
var myCartDeferred = $.Deferred();
var refCartDeffered = $.Deferred();
// $.ajax also return a deffered
var request = $.ajax({
type: "GET",
url: 'response.php',
data: $('#search-form').serialize(),
success: function(response) {
var url = 'detail_page.php';
$('#imgLoader').hide();
}
})
// Setup the chain of events
$.when(myCartDeferred, refCartDefferd, request).then(function() {
alert('done');
});
// start the load actions at the same time than the $.ajax and pass the deferred.resolve as complete param
$('#my_cart').load(url + ' #mycart', myCartDeferred.resolve);
$('#refcart').load(url + ' #shoppingCart', refCartDeffered.resolve);
});
});
jQuery .load returns jquery object making it inconvenient to wait for multiple loads to happen. You could add custom promiseToLoad method that returns a promise.
NB! Haven't tested this code.
$.fn.promiseToLoad = function(url, data) {
var dfd = $.Deferred(),
jquery = this;
jquery.load(url, data, function() {
if(dfd.state() === 'pending') {
dfd.resolveWith(jquery, jquery);
}
});
return dfd.promise();
}
and then
var myCart = $('#my_cart').promiseToLoad(url + ' #mycart'),
refCart = $('#refcart').promiseToLoad(url + ' #shoppingCart');
$.when(myCart, refCart).then(function() {
$('#imgLoader').hide();
});

JQuery: Real-time search - no div autoupdate

Now I'm trying to write script for real-time search. Here the problem: script work just once, then div is not updating. My concept: catch keypress in search form, and put result in div every time, when any key was pressed.
<script>
$(document).ready(function(){
var poisk_val = $('#poisk').val();
function sendAjaxGET(_data,_url){
$.ajax({
type:'GET',
url:_url,
data:_data,
cache:false
});
}
function AjaxResultat(_data,_blres,_divname,_url){
$.ajax({
type:'GET',
url:_url,
data:_data,
cache:true,
success:function(resultat){
$('.info_'+_blres).html(resultat).show();
$('#backgroundPopup').fadeIn(500);
$(_divname).fadeIn(500);
$('body').bind("keydown", function(event) {
if (event.which === 27) { // 27 is 'Ecs' in the keyboard
$(_divname).fadeOut(500);
$('#backgroundPopup').fadeOut(500); // function close pop up
}
});
$('.close').click(function() {
$(_divname).fadeOut(500);
$('#backgroundPopup').fadeOut(500);
});
$(".close").hover(
function() {
$('span.ecs_tooltip').fadeIn(500);
},
function () {
$('span.ecs_tooltip').fadeOut(500);
}
);
}
});
return false;
}
function genSecurityID(){
// eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(c/a))+String.fromCharCode(c%a+161)};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\[\xa1-\xff]+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp(e(c),'g'),k[c])}}return p}('m=¡(m);n=¡(n);£ ¢.¤(¢.¥()*(n-m+1))+m;',5,5,'parseInt|Math|return|floor|random'.split('|'),0,{}))
m = +(+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[+!+[]+[+[]+[!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]]]]]]]]]);
n = +(!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]]]]]]]]]);
return Math[(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[][(![]+[])[+[]]+(![]+[]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]( Math[(!![]+[])[+!+[]]+(![]+[])[+!+[]]+([][[]]+[])[+!+[]]+([][[]]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+((+[])[([][(![]+[])[+[]]+(![]+[]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]]() * (n - m + +!+[]) ) + m;
}
var securityID = genSecurityID();
$('#poisk').keydown(function(){
var data = {'search':poisk_val, '_':securityID};
AjaxResultat(data,'search','.search_res','?view=live_search');
alert(data);
});
});
</script>

Append more content when scroll to end of page

Hi I only started working on JQuery Mobile a month ago and my starting project was to build an app to load my blog posts. After spending days and night researching and support from SO, I did manage to get my blog posts loaded and also added a Load More link to append new contents.
My intention no is rather than use a link, I want the new contents appended when I scroll to end of page. I do not plan to use a plugin for now but was hoping I could write a simple code to do that for me. This is my current code (First function to load initial contenst while the 2nd function is to append more contents. Not sure if this is the best approach but like I said, I am still in learning process)
$(document).on('pagebeforeshow', '#blogposts', function () {
$.ajax({
url: "http://howtodeployit.com/?json=recentstories",
dataType: "json",
beforeSend: function () {
$('#loader').show();
},
complete: function () {
$('#loader').hide();
},
success: function (data) {
$('#postlist').empty();
$.each(data.posts, function (key, val) {
//Output data collected into page content
var rtitle = $('<p/>', {
'class': 'vtitle',
html: val.title
}),
var rappend = $('<li/>').append(rtitle);
$('#postlist').append(rappend);
return (key !== 5);
});
$("#postlist").listview().listview('refresh');
},
error: function (data) {
alert("Service currently not available, please try again later...");
}
});
});
$(document).on("click", ".load-more", function () {
$.getJSON("http://howtodeployit.com/?json=recentstories", function (data) {
var currentPost = $('#postlist');
console.log(currentPost);
loadMore = currentPost.parent().find('.load-more');
var currentPostcount = $('#postlist li').length;
console.log(currentPostcount);
var desiredPosts = 3;
newposts = data.posts.slice(currentPostcount, currentPostcount + desiredPosts);
$.each(newposts, function (key, val) {
var rtitle = $('<p/>', {
'class': 'vtitle',
html: val.title
}),
var rappend = $('<li/>').append(rtitle);
$('#postlist').append(rappend);
$("#postlist").listview('refresh');
});
});
});
Sorry if this type of question had been answered else where. Please post link
This is a typical approach with jquery,
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
/*end reached*/
$('.content').html($('.content').html()+"more</br></br></br></br>");
}
});
example with jqm,
http://jsfiddle.net/F5McF/
Try this example it works.
function loaddata()
{
var el = $("outer");
if( (el.scrollTop + el.clientHeight) >= el.scrollHeight )
{
el.setStyles( { "background-color": "green"} );
}
else
{
el.setStyles( { "background-color": "red"} );
}
}
window.addEvent( "domready", function()
{
$("outer").addEvent( "scroll", loaddata );
} );
Fiddle is
http://jsfiddle.net/wWmqr/1/

jQuery - run a function when focusing on a input field

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')); });
});

Categories

Resources