call javascript function on link click - javascript

I want to set a cookie value when user clicks on a link.
I am using the following code:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="../../Scripts/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
function changeLang(lang) {
$.cookie('myCulture', lang);
window.location.reload();
return false;
}
});
</script>
HTML
<img src="../../Content/images/danishFlag.png" height="35px" width="35px"/>
<img src="../../Content/images/swedishFlag.png" height="35px" width="35px"/>
It looks like very simple code, but when I click on the link, there is an error in the browser.
It says.
ReferenceError: changeLang is not defined
changeLang("da-DK");
Where am I doing wrong??

you are defining the function inside the document ready scope, so it's not global therefore not available in the global scope
define it as a global simply by removing the var declaration or using window.changeLang = function
$(document).ready(function () {
changeLang = function(lang) {
document.cookie = 'myCulture' + lang;
window.location.reload();
return false;
}
});

define function outside of the jquery block
$(document).ready(function () {
});
function changeLang(lang) {
$.cookie('myCulture', lang);
window.location.reload();
return false;
}

Try moving the ChangeLang function to outside of the Document Ready section.
Also, if running in FireFox with Firebug you can experiment with executing the function directly from the Console.
Good luck

Please do not attach js functions in html like this.
You're using jquery so just do this:
$(document).ready(function () {
function changeLang() {
$.cookie('myCulture', $(this).data('lang'));
window.location.reload();
return false;
}
$('.link').on('click', changeLang);
});
and then in html:
...

$(document).ready(function () {
});
function changeLang(lang) {
document.cookie = 'myCulture=' + lang;
window.location.reload();
return false;
}
This will work for you.

Related

Make function not global in script tag

I have only ONE function inside script tag in my HTML and will be used for event click. Is it possible to make this function not in global scope?
<script type="text/javascript">
function myFunction(sender, args) {
}
</script>
You can use IIFE, and register event handlers in that only, something like this
(function () {
function myFunction(sender, args) {}
$(".your_button").on("click", function () {
myFunction();
});
})();
Similar to IIFE, as you've tagged this [jquery], you can wrap it all in doc.ready:
<script type="text/javascript">
$(function() {
function myFunction(sender, args) {
}
// example use:
$(".button").click(function() { myFunction(this); });
});
</script>
myFunction will only be available to code within the { } of the doc.ready.
Note: if you're using onclick= in your HTML, it won't be able to find functions that are not global.
Maybe if you use let as the type of class, combined with a lambda(arrow) expression?
let myFunction = (sender, args) => {
}
Check this out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Passing function as a parameter into another function error

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.

Calling a function (ex. namespace.show) by name

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/

how to call function in jquery from javascript

<script type="text/javascript" src="jscripts/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert("funciton");
$(function(){
$.fn.gotof(){
alert("I am calling form jquery");
}
});
});
</script>
<input type="button" onclick="dofunc();">
<script type="text/javascript">
function dofunc(){
gotof();
}
</script>
how do i call gotof() that is present in jquery
and below is the code written over jsfiddle
There are a few errors in your code. Fixed it should look like this:
$.fn.gotof = function() { // has to be defined as a function, does not need to be inside a nested document ready function
alert("I am calling form jquery");
};
$(document).ready(function() {
alert("function is ready to use now");
});
function dofunc() {
$.fn.gotof(); // can call it using $.fn.gotof(), but it should really be called properly via a selector $('div').gotof();
}
http://jsfiddle.net/pSJL4/8/
Check out http://docs.jquery.com/Plugins/Authoring - this should answer your questior. You also are not defining your function correctly; instead of
$.fn.gotof(){
alert("I am calling form jquery");
}
you need
$.fn.gotof = function(){
alert("I am calling from jquery");
};

How to call a function within $(document).ready from outside it

How do you call function lol() from outside the $(document).ready() for example:
$(document).ready(function(){
function lol(){
alert('lol');
}
});
Tried:
$(document).ready(function(){
lol();
});
And simply:
lol();
It must be called within an outside javascript like:
function dostuff(url){
lol(); // call the function lol() thats inside the $(document).ready()
}
Define the function on the window object to make it global from within another function scope:
$(document).ready(function(){
window.lol = function(){
alert('lol');
}
});
Outside of the block that function is defined in, it is out of scope and you won't be able to call it.
There is however no need to define the function there. Why not simply:
function lol() {
alert("lol");
}
$(function() {
lol(); //works
});
function dostuff(url) {
lol(); // also works
}
You could define the function globally like this:
$(function() {
lol = function() {
alert("lol");
};
});
$(function() {
lol();
});
That works but not recommended. If you're going to define something in the global namespace you should use the first method.
You don't need and of that - If a function is defined outside of Document.Ready - but you want to call in it Document.Ready - this is how you do it - these answer led me in the wrong direction, don't type function again, just the name of the function.
$(document).ready(function () {
fnGetContent();
});
Where fnGetContent is here:
function fnGetContent(keyword) {
var NewKeyword = keyword.tag;
var type = keyword.type;
$.ajax({ .......
Short version: you can't, it's out of scope. Define your method like this so it's available:
function lol(){
alert('lol');
}
$(function(){
lol();
});
What about the case where Prototype is installed with jQuery and we have noconflicts set for jQuery?
jQuery(document).ready(function($){
window.lol = function(){
$.('#funnyThat').html("LOL");
}
});
Now we can call lol from anywhere but did we introduce a conflict with Prototype?

Categories

Resources