how to use noConflict for 2 js functions? - javascript

I have a different js framework and it stop below script.
So I read that I must using The noConflict() Method.
I try do it but just first function works. and second function do not works!
(if replace loction these two functions,Always only first function works.
what is my mistake?
I used this tutorial on w3school to do it.
http://www.w3schools.com/jquery/jquery_noconflict.asp
Also I try var jq = $.noConflict(); and other method.
I use this script inline in my html codes.
function checkCitySelect()
{
$.noConflict();
jQuery(document).ready(function($){
$("#province, #county, #district,#selectSubject").on('change', function() {
var txt;
var type = this.id;
txt = $("#"+type).val();
$.post("ajax/validation.php", {value: txt,id: type}, function(result){
if(type == 'province')
$("#county").empty().append(result);
else if(type == 'county')
$("#district").empty().append(result);
else if(type == 'district')
{
setAddressMap2("Paris, France");
}
else if(type == 'selectSubject')
{
$("#selectSubject").after(result);
}
});
});
});
}
function setAddressMap2(whereis)
{
$.noConflict();
jQuery(document).ready(function($){
$("#signup_map").gmap3({
getlatlng:{
address: whereis,
callback: function(results){
if ( !results ) return;
$(this).gmap3({
marker:{
latLng:results[0].geometry.location
}
});
}
}
});
});
}
checkCitySelect();
setAddressMap2("JAPAN");
</script>

Related

How to optimize this javascript duplicates

I wrote this code, but since I'm just starting to learn JS, can't figure out the best way to optimize this code. So made a duplicates for every if statement.
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$('.lang').hide();
$('.lang-all').click(function(){
$('.lang-all').hide();
$('.lang').slideToggle(200);
});
} else {
$('.lang').show();
$('.lang-all').hide();
}
if(gender.length == gender.filter(":checked").length){
$('.gender').hide();
$('.gender-all').click(function(){
$('.gender-all').hide();
$('.gender').slideToggle(200);
});
} else {
$('.gender').show();
$('.gender-all').hide();
}
});
So this is my code, as you can see on line 15 if(gender... I have a duplicate of previous code, just changed variable from "lang" to "gender". Since I have more that two variables, I don't want to make duplicate of code for every each of them, so I hope there is a solution to optimize it.
You can write a function to let your code more abstract, see:
function isChecked(obj, jq1, jq2){
if(obj.length == obj.filter(":checked").length){
jq1.hide();
jq2.click(function(){
jq2.hide();
jq1.slideToggle(200);
});
} else {
jq1.show();
jq2.hide();
}
}
//Your jQuery code, more abstract
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
isChecked(lang, $('.lang'), $('.lang-all'));
isChecked(gender, $('.gender'), $('.gender-all'));
});
make a function which had similar functionality, then pass a parameter as a class or id
$(function() {
call('.lang');
call('.gender');
function call(langp){
var lang = $(langp+" input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$(langp).hide();
$(langp+'-all').click(function(){
$(langp+'-all').hide();
$(langp).slideToggle(200);
});
} else {
$(langp).show();
$(langp+'-all').hide();
}
}
});

Not able to load dynamically the CDN of jquery, bootstrap, D3.js, knockout.js using jquery

Not able to load dynamically the CDN of jquery, bootstrap, D3.js, knockout.js using jquery. i am using jquerycdn variable to pass to the loadscript() when checkjquery() is false. But when i am passing still the jquery CDN is not loading. Same issue facing with the remaining files like bootstrap, D3.js, knockout.js etc. All these file CDN's are kept in one js file.
Please check the below code:-
this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"
Initialize.prototype.checkJQuery = function () {
if (window.jQuery) {
return true;
} else {
return false;
}
};
if (!this.checkJQuery ()) {
console.log("jquerynot available")
this.loadJQuery ();
if (!this.checkJQuery ()) {
throw "Error loading jquery"
}
} else {
console.log("jquery available")
}
Initialize.prototype.loadJQuery = function () {
// var js_code = atob(this.jqueryStr);
// eval(js_code);
this.loadScript(this.jqueryCDN);
};
Initialize.prototype.loadScript = function (src) {
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src', src);
document.head.appendChild(my_awesome_script);
}
You need to give jQuery time to load before checking to see that it's loaded. An onload trigger would be better than timeout, but here's your code working.
function Initialize() {
var self = this;
this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"
if (!this.checkJQuery()) {
console.log("jquery not available")
this.loadJQuery();
setTimeout(function() {
if (!self.checkJQuery()) {
throw "Error loading jquery"
} else {
alert("jQuery loaded!");
}
}, 2500);
} else {
console.log("jquery available")
}
}
Initialize.prototype.checkJQuery = function() {
if (window.jQuery) {
return true;
} else {
return false;
}
};
Initialize.prototype.loadJQuery = function() {
// var js_code = atob(this.jqueryStr);
// eval(js_code);
this.loadScript(this.jqueryCDN);
};
Initialize.prototype.loadScript = function(src) {
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src', src);
document.body.appendChild(my_awesome_script);
}
var i = new Initialize();
You might also look at this approach.

2 javascripts are conflicting

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>

Jquery Impromptu function running order problem

I I hafe a function which uses the $.prompt Jquery (impromptu) pluggin. This works fine except that whenever I call the function it is run right at the end of the function that it was called from.
Here is the function...
function addfile(){
var txt = '<?php echo $JSString; ?>';
function mycallbackform(v,m,f){
if(v != undefined)
var newText = f.alertName + " , " + f.alertName.replace("-", " ").replace(".php", "");
alert(newText);
}
$.prompt(txt,{
callback: mycallbackform,
buttons: { Add: 'add', Cancel: 'cancel' }
});
}
The PHP bit just adds the html string in and is working fine, the problem still occours when using text (i.e. 'this is a prompt').
Whenever I call addfile() from JS it will run last. e.g. ...
function newfunction()
{
prompt("Before");
addfile();
prompt("after");
}
... will display do the following ...
Prompt - 'Before'
Prompt - 'After'
addfile();
No matter what I do the addfile() will always run last which confuses me. I'm pretty new to these things so If i'm doing anything really stupid please don't be afraid to point it out.Subnote: The function is sitting in the header of my php file so that the <?php echo $JSString; ?> works. I have removed the php and inserted the function into an external JS file but the same problem prevails so it is the $.prompt which seems to be causing the problem not the JS
Any ideas as to how to get this JS to behave greatly appreciated.Many thanks
your prompt function is asynchronous, that's why it accepts a callback function as parameter.
Try this:
prompt(
txt,
{callback: function() {
addfile();
prompt("after");
}}
);
Above approach is not working . Below is the code portion that. Alert is being displayed before blocking the page. I am using blockUI along with it.
function blockPage(){
$.blockUI({
message: "<img src='loading.gif'/>",
color: 'transparent',
backgroundcolor: '#777777',
top: $(window).height()/2
});
return true;
}
function dosomethingelse(){
var aa;
var bb;
alert("c");
}
function createOverlay(){
var overlaySubmit = function(e,v,m,f){
if(v === -1){
alert("Closing the prompt");
$.prompt.close();
return false;
} else if(v === 1){
dosomethingelse();
//blockPage();
return false;
}
};
var prompt = $.prompt(
"This is a test prompt",
{
opacity: 0.3,
buttons: {Add: 1, Cancel: -1},
position: {x: 300},
prefix: 'jqi',
submit: function(e,v,m,f){
blockPage();
try{
alert(g);
} catch (err){
alert("here");
}
overlaySubmit(e,v,m,f);
}
});
prompt.bind('promptsubmit',blockPage);
}
<!-- Ajax-->
$('#ajax').click(function(){
$.ajaxSetup({async:false});
$.ajax({
url: "test-server.txt",
success: function(response){
createOverlay();
return false;
},
error: function(){
return false;
}
});
});

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