I'm trying to make a complementary library to jQuery but not jQuery plugin, nor jQuery extension:
First Function:
function w(id) {
return $(id);
}
It works as jQuery plugin:
$.prototype.test = function(){
console.log("testing");
}
w("div").test(); // test
What I want is this, as a prototype function of w(), but doesn't works:
w.prototype.test = function(){
console.log("testing");
}
w("div").test(); // test
Thanks,
.........................................
It works with:
w.prototype = jQuery.prototype;
Thanks SLaks!
But when it does, doesn't works with:
w.prototype = {
test: function(){
console.log("testing");
}}
.......................
Now it's works;
function w(id) {
return $(id);
}
w.prototype = jQuery.prototype;
w.prototype.extend({
test:function(){
console.log("testing");
}
});
Thanks for help!!!
You want
w.prototype = jQuery.prototype;
Related
The toggle() method was deprecated in jQuery version 1.8, and removed in version 1.9. Documentation
How can use something like toggle() function in jQuery 1.11+ ?
Full Code in Fiddle
<script>
function test(){
$("*:contains(ไทย):last").text("English");
}
function test2(){
$("*:contains(English):last").text("ไทย");
}
$("#click").toggle(
test(),
test2();
});
</script>
I dont know about this behaviour, but there is my solution:
function test(){
$("*:contains(ไทย):last").text("English");
}
function test2(){
$("*:contains(English):last").text("ไทย");
}
var el = document.getElementById("click");
$(el).click(function (e) {
el.foo.apply(this, arguments);
});
el.foo = test;
el.toggle = function () {
el.foo = el.foo === test ? test2 : test;
};
I have implemented several jQuery plugins for my current project.
Since some plugins have functions with the same name, the one called in the last one defined.
Here is the definition of my first plugin:
$(function($)
{
$.fn.initPlugin1 = function(parameters)
{
var defaultParameters = {};
$(this).data('parameters', $.extend(defaultParameters, parameters));
return $(this);
};
$.fn.function1 = function(){ console.log('Function 1.'); };
$.fn.callFunction = function(){ $(this).function1(); };
});
And here is the definition of my second plugin:
$(function($)
{
$.fn.initPlugin2 = function(parameters)
{
var defaultParameters = {};
$(this).data('parameters', $.extend(defaultParameters, parameters));
return $(this);
};
$.fn.function2 = function(){ console.log('Function 2.'); };
$.fn.callFunction = function(){ $(this).function2(); };
});
I have also this scenario :
$("#div1").initPlugin1().callFunction();
$("#div2").initPlugin2().callFunction();
For this specific scenario the consoles shows: Function 2. Function 2.
In fact, since the callFunction() is also defined in the second plugin, this is the one used.
I would like some advise on what is the best way to solve this problem.
Is it possible to create a thing similiar to a namespace ?
Thank to #syms answer, I have created the following example.
Plugin1:
$(function($) {
$.fn.initPlugin1 = function() {
console.log('Initialized Plugin1');
return $(this);
};
$.fn.initPlugin1.testFunction = function() {
$(this).append('Function 1.');
};
});
Plugin2:
$(function($) {
$.fn.initPlugin2 = function() {
console.log('Initialized Plugin2');
return $(this);
};
$.fn.initPlugin2.testFunction = function() {
$(this).append('Function 2.');
};
});
Main:
(function($)
{
$(document).ready(
function()
{
$("#div1").initPlugin1(); //Run correctly
$("#div2").initPlugin2(); //Run correctly
$("#div1").initPlugin1.testFunction(); //Fail
$("#div2").initPlugin2.testFunction(); //Fail
});
})(jQuery);
When I run my code, I got the following error: Cannot read property 'createDocumentFragment' of null.
Apparently, the this object is corrupted.
you can try this,
$(function($) {
$.fn.initPlugin1 = function() {
console.log('Initialized Plugin1');
return $(this);
};
});
$(function($) {
$.fn.initPlugin2 = function() {
console.log('Initialized Plugin2');
return $(this);
};
$.fn.callFunction = function(param) {
$(this).append(param);
};
});
(function($) {
$(document).ready(
function() {
$("#div1").initPlugin1(); //Run correctly
$("#div2").initPlugin2(); //Run correctly
$("#div1").initPlugin1().callFunction('function1');
$("#div2").initPlugin2().callFunction('function2');
});
})(jQuery);
We all know that use the val() will not trigger the change event, so we also use .trigger('change') behind the val().
But the problem is that someone write the val() did't with trigger() and it's a external file that I can't edit it.
So, how can I detect value change through some code same like below:
$('.elem').on('change', function(){
// do something
});
My suggestion is to override jquery's val()
var originalValFn = jQuery.fn.val;
jQuery.fn.val = function() {
this.trigger('change');
originalValFn.apply( this, arguments );
}
jsfiddle: http://jsfiddle.net/2L7hohjz/js
var originalValFn = jQuery.fn.val;
function getErrorObject(){
try { throw Error('') } catch(err) { return err; }
}
jQuery.fn.val = function() {
if ($(this).hasClass( "element" )) {
var err = getErrorObject();
var caller_line = err.stack.split("\n")[4];
var index = caller_line.indexOf("at ");
var clean = caller_line.slice(index+2, caller_line.length);
console.log(clean);
console.log(arguments);
}
originalValFn.apply( this, arguments );
};
Try:
setTimeout(function() {
if (currentValue != previousValue)
{
// do something
}
}, 500);
Thank you,
I commonly use the solution from this post to get around problems like this one:
hidden input change event
watchField('.elem', function(){
//do some stuff here
});
function watchField(selector, callback) {
var input = $(selector);
var oldvalue = input.val();
setInterval(function(){
if (input.val()!=oldvalue){
oldvalue = input.val();
callback();
}
}, 100);
}
Try:
$('.elem').on('keyUp', function(){
// do something
});
or
$('.elem').on('lostFocus', function(){
// do something
});
Thank you,
Here's what I have in require.config.shim (in main.js):
'jquery.tabs':{
deps:['jquery'],
exports: '$'
},
And here are the relevant parts in my module:
define(['jquery','underscore','backbone','tools','jquery.tabs'], function($,_,Backbone,Tools){
//SNIP
myView = Backbone.View.extend({
//SNIP
render: function(){
//SNIP
var el = tmp.find(".tabholder")
console.log(el); // not empty
console.log($.fn.createTabHolder); //not empty
el.createTabHolder(); //TypeError: el.createTabHolder is not a function
//el.createPopup(); //different plugin, same error here
//el.hide(); // this works just fine
//SNIP
},
//SNIP
});
//SNIP
});
It works just fine when I'm using Chrome or running it from localhost, but I get "TypeError: el.createTabHolder is not a function" when I run it from server using Firefox (22.0).
Here's the plugin code just in case, it used to work just fine before I switched to using requirejs:
(function (jQuery){
jQuery.fn.createTabHolder = function (){
this.html("");
var tbar = $("<div/>",{
class:"tabbar padfix noselect"
});
tbar.appendTo(this);
var tholder = $("<div/>",{
class:"tabcontainer"
});
tholder.appendTo(this);
};
jQuery.fn.addTab = function(title,data,index, constructor,model,obj){
var self=this;
var ts = $("<span/>",{
class:"tabselector",
html:title,
});
var tab = $("<div/>",{
class:"tabselector_tab"
});
if(data.jQuery)
tab.append(data);
else
tab.html(data);
tab.appendTo(this.find(".tabcontainer"));
if(constructor)
ts.one("click",{element:tab,model:model,obj:obj},constructor);
ts.on("click",function(){
self.find(".selectedtab").removeClass("selectedtab");
tab.addClass("selectedtab");
self.find(".activetabselector").removeClass("activetabselector");
ts.addClass("activetabselector");
});
if(this.find(".activetabselector").length==0)
ts.trigger("click");
ts.appendTo(this.find(".tabbar"));
}
return jQuery;
})(jQuery);
No idea what's going on, and can't really provide anything else than that.
Maybe there are different versions of jquery there. Try this:
define(['jquery'], function (jQuery){
jQuery.fn.createTabHolder = function (){
// ...
};
});
instead of this:
(function (jQuery){
jQuery.fn.createTabHolder = function (){
// ...
};
})(jQuery);
Replaced
var el = tmp.find(".tabholder");
with this:
var el = $(tmp.find(".tabholder"));
and it seems to work now, I have no idea why tho, prob fixed some weird timing issue or something. Trial & error ftw.
I've added a javascript element I found in a guide. It is as follows
$(document).ready(function ()
{
$('.dropdownbutton').click(function ()
{
$.post("send.php", $(".mycontactform").serialize(), function (data)
{
});
$('#success').html('Message sent!');
$('#success').hide(2000);
});
});
The existing javascript was
function toggleDisplayWait(divId, imgId, durationmSec) {
if(!$(divId).visible()) {
move = Effect.BlindDown;
newImage = "./img/minus.png";
}
else {
move = Effect.BlindUp;
newImage = "./img/plus.png";
}
move(divId, {duration: durationmSec / 1000.0 });
setTimeout(function() { $(imgId).src = newImage; }, durationmSec)
}
function BDEffect(divId, imgId)
{
/* new Effect.BlindDown(element, {duration:3});
}*/
if(!$(divId).visible())
{
move = Effect.BlindDown;
newImage = "./img/feedbacktab_open.png";
setTimeout(function() { $(imgId).src = newImage; }, 0)
}
else
{
move = Effect.BlindUp;
newImage = "./img/feedbacktab.png";
setTimeout(function() { $(imgId).src = newImage; }, 2)
}
move(divId, {duration:2});
/*setTimeout(function() { $(imgId).src = newImage; }, 0)*/
}
</script>
But neither the OLD code nor the NEW code works now.
Error console now reporting "$(divId).visible is not a function" when i try to use the old script
The old code looks like it's using the Prototype framework, and the new code is using jQuery.
When you use the two together, you need to use jQuery's noConflict() so that they don't both try to use the $ variable.
First, after including the jQuery library, add a script like this:
<script>
jQuery.noConflict()
</script>
Then modify your jQuery code to look like this:
jQuery(function ($) {
$('.dropdownbutton').click(function() {
$.post("send.php", $(".mycontactform").serialize(), function(data) {});
$('#success').html('Message sent!');
$('#success').hide(2000);
});
With noConflict, everywhere you want to use jQuery, you must use the jQuery variable instead of $. However, you can still pass $ in as a local variable, and it will not conflict with Prototype.
Also, note that I changed your document.ready(function() { ... }) function into jQuery's shorthand version: jQuery(function() { ... }). The function will also get passed the jQuery object, which I name $ for convenience.