In this code, only the "test" in added to the class "team-member", probably because the second this is the function and not the element.
How can I do something of the main element(class) "team-member" inside a function ?
$(document).ready(function () {
$('.team-member').SimpleSlider();
});
(function ($) {
$.fn.SimpleSlider = function (options) {
Initial();
$(this).addClass("test");
function Initial() {
$(this).addClass("test2");
};
}(jQuery));
I found a solution, pass "this" as a parameter
$.fn.SimpleSlider = function (options) {
Initial(this);
$(this).addClass("test");
function Initial(obj) {
$(obj).addClass("test2");
}
Related
I've picked up some JavaScript to work on as follows (very much simplified!)
var namespace = {
init: function (config) {
// do stuff, all ok so far
},
events: function () {
$('#id').on('click', '.class', function (event) {
alert('hello')
}
}};
What I am trying to figure out is how, from the init: block of code, can I call the code in the click event that does alert('hello')?
I realise moving the alert('hello') into a function would help (so I can call the function from init and click), but how would I define the function in this namespace and call it from two places?
What I'm aiming at, and guessing the solution is something like this:
var namespace = {
init: function (config) {
// do stuff
hello
},
hello: function() {
alert('hello');
},
events: function () {
$('#id').on('click', '.class', function (event) {
hello
}
};
I will have to pass event param from click into hello.
I'm still trying to figure out how namespaces work in js... Thanks for any help offered.
Use the this keyword.
var namespace = {
init: function (config) {
// do stuff
this.hello();
},
hello: function() {
alert('hello');
},
events: function () {
$('#id').on('click', '.class', function (event) {
this.hello();
}.bind(this));
}
};
Example of how to use it:
namespace.init();
namespace.events(); // then do a click on the html where you have the class "class"
You can use one of the powerful functionality of Javascript - Closures. Refer the Closures topic in this MDN Documentation.
var namespace = (function(){
function hello(){
alert("hello");
}
return {
init: function (config) {
console.log("called init");
hello();
console.log("called hello from init")
},
events: function () {
$('#but').on('click', function (event) {
hello();
console.log("called hello from events")
});
}
}
})();
namespace.init();
namespace.events();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="but">Click</button>
I'm using jquery and in my app.js file I have tow main functions:
$(document).ready(function (){});
$(window).on("load", function (){});
my code looks like this:
$(function () {
// code
// code
function myFunction(){
// code
}
});
$(window).on("load", function () {
// I want to use myFunction() here but I cant because it's not accessible from here
myFunction();
});
is there a way to do this?
window.lib = {
onWindowLoad: function () {
...
},
onDocReady: function() {
...
},
evenmore: {
nested: function(){
...
}
}
}
$(window).on("load", function () {
lib.onWindowLoad();
});
There would be many other ways to do so.
In case, if you need to read something somewhere, that's here
I'm getting a 'navigateTo is not defined' error in my JS with the following. I'm pretty sure I have passed the function navigateTo as a parameter to the openCart() function so unsure where I'm going wrong?
$(function() {
var form = $('form#checkout-form'),
$sections = $('[data-step]');
function navigateTo(index) {
$sections.removeClass('is--active').eq(index).addClass('is--active');
}
});
$(document).on('click', 'nav.main a.cart', function(e) {
openCart();
});
function openCart(navigateTo) {
navigateTo(1);
disableScroll = false;
}
your function openCart should go to inside the dom ready function otherwise it doesn't call the function and another thing you need to pass the callback as parameter navigateTo into the opencart function like openCart(navigateTo);
$(function() {
var form = $('form#checkout-form'),
$sections = $('[data-step]');
function navigateTo(index) {
alert(2);
$sections.removeClass('is--active').eq(index).addClass('is--active');
}
$(document).on('click', 'div', function(e) {
openCart(navigateTo);
});
function openCart(navigateTo) {
navigateTo(1);
disableScroll = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hahah</div>
It's a scope issue. Wrap your whole script in a closure and you'll be fine;
(function($) {
// your script here
})(jQuery)
But get rid of the $(function() { } around the first block as well.
I'm trying to improve my code overall, although the following code does work, I want to avoid using _this (to me a hacky way of doing it ), and start using either .call/.apply or .bind to set the context of this on the following example.
Here is the code and the link to jsfiddler link.
(function (window, $) {
'use strict';
var ButtonEffect, button;
Function Constructor
ButtonEffect = function (elem) {
this.button = $( elem );
};
//Prototype Chain
ButtonEffect.prototype = {
addEffect : function (ref) {
return $(this.button, ref).addClass('custom-effect-1');
},
btnObserver : function () {
//Don't want to use this approach
var _this = this;
this.button.on({
click : function () {
//Want to call addEffect without using _this/that #hack
_this.addEffect($(this));
}
});
}
};
button = new ButtonEffect('.my-button');
button.btnObserver();
(window, window.jQuery));
Here is another Solution i came up with link
Seems more appropriate to use the built in jQuery methods for passing data to the event handler, that way this still references the element inside the handler
(function (window, $) {
'use strict';
var ButtonEffect, button;
ButtonEffect = function (elem) {
this.button = $( elem );
};
ButtonEffect.prototype = {
addEffect : function (ref) {
return $(this.button, ref).addClass('custom-effect-1');
},
btnObserver : function () {
this.button.on( {
click : function (e) {
e.data.scope.addEffect($(this));
}
}, {scope: this});
}
};
button = new ButtonEffect('.my-button');
button.btnObserver();
}(window, window.jQuery));
FIDDLE
You can change your code like this:
btnObserver : function () {
this.button.on({
click : function (ev) {
this.addEffect($(ev.currentTarget));
}.bind(this)
});
}
ev.currentTarget is usually the same as what this would be if bind is not used. And bind makes it so that the value of this inside your event handler is the same as the scope in which bind executes. I have a fiddle.
I want to call a function with a namespace based on its name.
Perhaps some background: What I want is, dynamically bind pages via $.mobile.loadPage(inStrUrl, { showLoadMsg: false }); and then, based on the current page, invoke a function within a loaded page. For example: each page has a showFilter function, the Event is attached to a main.html - page which should call the matching function in the current page.
I also tried some solutions, with jquery too, but nothing works for me.
This is my function code:
function namespace() { }
namespace.showFilter = function () {
alert("Test");
}
And want to "invoke" or "call" it via its name.
This is what i tried at least.
$(document).ready(function() {
var fn = window["namespace.showFilter"];
fn();
});
I get error TypeError: fn is not a function
Here is a fiddle http://jsfiddle.net/xBCes/1/
You can call it in the following way:
$(document).ready(function() {
window["namespace"]["showFilter"]();
});
or
$(document).ready(function() {
window["namespace"].showFilter();
});
or
$(document).ready(function() {
window.namespace.showFilter();
});
I found that I had to manually set it to window.
window.namespace = function() { }
window.namespace.showFilter = function () {
alert("Test");
};
$(document).ready(function() {
var fn = window["namespace"]["showFilter"];
fn();
});
http://jsfiddle.net/xBCes/4/
Like this:
$(function() {
window.namespace.showFilter();
});
P.S. I shortened the $(document).ready(...)
function namespace() {}
namespace.showFilter = function () {
alert("Test");
}
$(document).ready(function() {
var fn = namespace.showFilter();
fn();
});
http://jsfiddle.net/xBCes/3/