I have a page with a linked javascript object:
//the constructor function
function NewsScroller() {
}
//now put some config objects using the JSON structure
NewsScroller.prototype.config = {
serviceUrl : '/NewsProvider.svc/rest/GetNews/',
pageIndex : 0
}
//the argumented constuctor for this object
NewsScroller.prototype.init = function () {
this.getNews(this.config.pageIndex);
console.log(this.config.pageIndex);
}
NewsScroller.prototype.decreasePage = function () {
console.log('current page index ' + this.config.pageIndex);
}
Then I have the page ready declaration:
<script>
$(document).ready(function () {
var newsScrollerForPage = new NewsScroller();
newsScrollerForPage.init();
newsScrollerForPage.decreasePage();
});
</script>
Which produces the result:
current page index 0
I want to call the function from an anchor tag so I have:
<div class="scroller-left">
<a id="scroller-left-a" href="javascript:newsScrollerForPage.decreasePage();">
<img src="/Images/Left-Scroller.jpg"/>
</a>
</div>
But when I click the anchor I get:
newsScrollerForPage is not defined
Why is this? Surely I should be able to call the object and function just like I did in the .ready method?
You define the newsScrollerForPage inside the ready function with local scope (by using "var"), you can't use it outside of there except if you define a function in the same scope which uses it (scope is evaluated from where functions are defined, not from where they are called).
You can quickly fix the issue by taking away the var from before it (making it more global rather than local in scope) but I wouldn't suggest this as the best solution.
Better would be to link up the anchor like this:
$(document).ready(function () {
var newsScrollerForPage = new NewsScroller();
newsScrollerForPage.init();
newsScrollerForPage.decreasePage();
document.getElementById("scroller-left-a").onclick=function()
{
newsScrollerForPage.decreasePage();
return false;
}
});
and removing the href from the HTML element.
Related
In my HTML, this works
<div id="portfolio1" onclick="changeMainFrame('lib/portfolio1.html')">
to trigger the following function:
function changeMainFrame(srcURL){
var target = document.getElementById("mainFrame");
target.src = srcURL;
}
I want to migrate it to my javascript doc. But this does not work:
document.getElementById("portfolio1").onclick = changeMainFrame("lib/portfolio1.html");
I can not find out how to fix this. Any hints? Cannot find a similar situation anywhere for something so simple yet time consuming.
document.getElementById("portfolio1").onclick = function() {
changeMainFrame("lib/portfolio1.html");
}
You're calling the function changeMainFrame. What you want to do is supply a function wrapper.
document.getElementById("portfolio1").onclick = function() {
changeMainFrame("lib/portfolio1.html");
}
function changeMainFrame(txt) {
alert(txt);
}
<div id="portfolio1">Click Me</div>
You need to assign a function to document.getElementById("portfolio1").onclick which will be called when that element gets clicked. The problem is that instead of assigning a function, you assigned the result of invoking/calling that function. What you can do instead is provide a function in which inside it you call changeMainFrame:
document.getElementById("portfolio1").onclick = function() {
changeMainFrame("lib/portfolio1.html");
};
You need to either use .onclick or the onclick attribute. Both of them require a handler function, and what you were passing was just the result of running your changeMainFrame function (null). Wrapping it in a function() { } yields your expected result.
function changeMainFrame(srcURL){
var target = document.getElementById("mainFrame");
target.src = srcURL;
}
document.getElementById("portfolio1").onclick = function(){changeMainFrame('https://codepen.io')}
<div id="portfolio1">go to codepen.io</div>
<iframe id="mainFrame" src="https://example.com"></iframe>
I have a panel widget with a button. Clicking the button should execute some global actions related to all such widgets and after that execute some local actions related to this widget instance only. Global actions are binded in a separate javascript file by CSS class like this:
var App = function ()
{
var handleWidgetButton = function ()
{
$('.widgetBtn').on('click', function (e)
{
// do smth global
});
return {
init: function ()
{
handleWidgetButton();
}
};
}
}();
jQuery(document).ready(function()
{
App.init();
});
And in the html file local script is like this:
$("#widgetBtn1234").click(function (e)
{
// do smth local
});
Currently local script is executed first and global only after while I want it to be the opposite. I tried to wrap local one also with document.ready and have it run after global but that doesn't seem to change the execution order. Is there any decent way to arrange global and local jQuery bindings to the same element?
The problem you're having comes from using jQuery's .ready() function to initialize App, while you seem to have no such wrapper in your local code. Try the following instead:
var App = function ()
{
var handleWidgetButton = function ()
{
$('.widgetBtn').on('click', function (e)
{
// do smth global
});
return {
init: function ()
{
handleWidgetButton();
}
};
}
}();
$(function()
{
App.init();
});
Then in your local JS:
$(function() {
$("#widgetBtn1234").click(function (e)
{
// do smth local
});
});
Note that $(function(){}) can be used as shorthand for $(document).ready(function(){});. Also, make sure your JS file is located before your local JS, as javascript runs sequentially.
Alternatively, you can use setTimeout() to ensure everything's loaded properly:
(function executeOnReady() {
setTimeout(function() {
// Set App.isInitialized = true in your App.init() function
if (App.isInitialized) runLocalJs();
// App.init() hasn't been called yet, so re-run this function
else executeOnReady();
}, 500);
})();
function runLocalJs() {
$("#widgetBtn1234").click(function (e)
{
// do smth local
});
};
How about this instead:
var widget = $("#widgetBtn1234").get(0);//get the vanilla dom element
var globalHandler = widget.onclick; //save old click handler
// clobber the old handler with a new handler, that calls the old handler when it's done
widget.onclick = function(e){
//do smth global by calling stored handler
globalHandler(e);
//afterward do smth local
};
There might be a more jqueryish way to write this, but I hope the concept works for you.
-------VVVV----keeping old answer for posterity----VVVV--------
Why not something like this?
var App = function ()
{
var handleWidgetButton = function ()
{
$('.widgetBtn').on('click', function (e)
{
// do smth global
if(this.id === 'widgetBtn1234'){
//do specific things for this one
}
});
return {
init: function ()
{
handleWidgetButton();
}
};
}
}();
Please excuse any syntax errors I might have made as I haven't actually tested this code.
Check out my simple JQ extension I created on jsbin.
http://jsbin.com/telofesevo/edit?js,console,output
It allows to call consequentially all defined personal click handlers after a global one, handle missed handlers case if necessary and easily reset all personal handlers.
I have a function defined as follows:
window.onload = function() {
var ids = document.getElementById("idname");
function myFunction(){
/...*use ids var in here*./
}
}
I am trying to call myFunction from button onclick in html:
<button onclick="myFunction();"></button>
But it says myFunction is not defined. I understand because this is inside window.onload. How can I fix this? I need window.onload because I need to use document.getElementById("testID") to get content.
I need window.onload because I need to use document.getElementById("testID") to get content
No, you don't need window.onload. You simply have to put the code somewhere after the element with ID testID in the document.
Example:
<div id="testID"></div>
<script>
var ids = document.getElementById("testID");
function myFunction(){
/...*use ids var in here*./
}
</script>
However, if you want to keep using window.onload, then I suggest to not use inline event handlers, but bind the handler with JS:
window.onload = function() {
var ids = document.getElementById("testID");
ids.onclick = function(event){
/...*use ids var in here*./
}
};
(that might be a good thing to do anyway).
Lastly, you can get the a reference to the element inside the event handler using this or event.target:
<div id="testID"></div>
<script>
document.getElementById("testID").onclick = function(event) {
// access element via `this` or `event.target`
};
</script>
Learn more about event handling.
You defined it within a function so it's locked to that scope. Maybe you want to define it outside of that:
function myFunction() {
var ids = document.getElementById("idname");
// ...
}
window.onload = function() {
// ...
}
As a note, this is extremely old-school JavaScript. You could clean this up considerably using something like jQuery which would look something like this:
$(function() {
// Any initialization after page load.
});
function myFunction() {
var ids = $('#idname');
// ...
}
i try to pass paramater to function. When i click the div it will alert the paramater that i pass
i have 2 file
index.html
script.js
here's what i try
Example 1
index.html
<div id="thediv" >
script.js
window.onload = initialize;
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = myFunction(" something ");
}
//end of bind
//function
function myFunction(parameter) { alert( parameter ) };
//end of all function
the trouble is the function its executed without click
Example 2
index.html
<div id="thediv" onclick="myfunction('something')" >
script.js
function myFunction(parameter) { alert( parameter ) };
yap its done with this but the trouble if i have many element in index.html it will painful to read which element have which listener
i want to separate my code into 3 section (similiar with example1)
the view(html element)
the element have which listener
the function
what should i do? or can i do this?
(i don't want to use another library)
Placing () (with any number of arguments in it) will call a function. The return value (undefined in this case) will then be assigned as the event handler.
If you want to assign a function, then you need to pass the function itself.
...onclick = myFunction;
If you want to give it arguments when it is called, then the easiest way is to create a new function and assign that.
...onclick = function () {
myFunction("arguments");
};
Your first solution logic is absolutely ok .. just need to assign a delegate ... what you are doing is calling the function .. So do something like this ...
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function () { myFunction(" something "); };
}
//end of bind
Instead of assign you invoke a function with myFunction();
Use it like this
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function(){
myFunction(" something ");
}
}
I have functions in side a document.ready and I want to call them using value inside a variable.. I tried to use window[variablename](); but it is not working inside document.ready but when called it directly it works..
think this is the function inside the document.ready
$(document).ready(function() {
function jhon(){
alert('works');
};
});
I'm getting function name from a variable,value of that variable is the name of the function..
below code will get the URL's hashed part example: #JHON and remove # and store it inside URLHASH variable..example: JHON
var urlhash = document.location.hash;
urlhash = urlhash.replace(/^.*#/, '');
when I called like this it is not working..
window.onload=function() {
window[urlhash]();
};
but when I call the function like this it is working fine..
window.onload=function() {
jhon();
};
Is it possible to call a function using variable value?
This:
window.onload=function() {
window[urlhashed]();
};
Contains a typo: urlhashed ought to be urlhash
window.onload=function() {
window[urlhash]();
};
In addition to that you have defined jhon() inside of another function, which capture's it in that enclosing functions scope.
if you want to have this work as intended you ought to change this:
$(document).ready(function() {
function jhon(){
alert('works');
};
});
to be more like this:
$(document).ready(function() {
window.jhon = function(){
alert('works');
};
});
Define the function jhon outside of $(document).ready. Otherwise, it'll be hidden, and thus inaccessible via window[function_name]:
function jhon(){
alert('works');
};
$(document).ready(function() {
var urlhash = document.location.hash;
urlhash = urlhash.replace(/^.*#/, '');
window[urlhash]();
});