I'm looking through a website's source code because I'm trying to learn to some basic Javascript. I understand the first part:
function count() {
...
}
I know that the function is called count, and doesn't take any arguments. The next function I don't understand:
$(function(){
...
});
Is the function called 'function'? And why is there a '$' symbol at the beginning. I've tried searching the internet, but google just ignores the '$'s and brackets and just searches for 'function'.
In addition, another thing I don't understand; the website has a single button that, when pressed, plays an audio file. The button is set up like so:
<a href="javascript:void()" id="button">
<img src="img/button.png" border="0">
</a>
What does javascript:void() do?
I'm sorry this isn't really a programming question, but I'm trying to learn Javascript and i figured I might have a look what other people are doing.
$ is the name (actually a reference to) of a function defined by the very popular jQuery library.
$( ) is calling the $ function
Inside the parenthesis you have an anonymous function definition.
$(function(){ console.log('test'); });
is pretty much the same as:
function nameNotImportant() { console.log('test'); }
$(nameNotImportant);
but it's more concise and you don't have to think of a name for that function.
As you probably noticed, nameNotImportant is not called. A reference to it is passed as parameter to the $ function to do as it wants with it, including call it. That is exactly what the $ function does when passed a function as parameter to it: it calls that function when the DOM is ready to be interacted with.
<a href="javascript:void()">
When an <a>nchor is clicked, the default action performed by the browser is to navigate to its href attribute. If you want it to not do that, you have to somehow interfere with the mechanism, for example by setting the href attribute to execute some javascript code that does nothing. I wouldn't consider it an example of good programming, but that is what it is used for.
I'm assuming you know that $ is an alias to jQuery.
$(function() {
// ...
});
is passing an anonymous function to the $ function, which can take a callback function. This function is run when the DOM is ready, so the more verbose form of this is
$(document).ready(function() {
// ...
});
In addition,
javascript:void()
is used to simply return undefined for a URL--aka the browser does not navigate to a page when you click on the link. javascript:void() is often used to allow the developer to bind JavaScript click events to the <a> tag.
Related
Coming from a C++ background, trying to work with an OO language that doesn't have explicit typing is a little more than a headache.
So I have dynamic elements for a webpage that are "controlled" by objects since there are tons of stuff I need to manage on each for it to work. The element is just the visual output of the data inside of the object itself, that's all I really need it for.
Except that I need the object to perform an internal function when it's clicked. That seems to be the biggest source of my headache thus far.
Javascript:
function onClick(file) //The external onClick function I use to try to get it to call from.
{
file.state = INUSE;
file.checkState();
}
function fileObject () { //The file object itself
this.element;
this.newElement();
//initialize stuff for the object
}
fileObject.prototype.newElement = function() { //creates a new element and sets its event listener
this.element.click(function() {onClick(this)});
}
fileObject.prototype.checkState = function() {/*does stuff*/} //apparently this is "not a function"
The error I get exactly is "file.checkState is not a function" from Firefox's console panel.
I'm still new to javascript, but after doing some debugging, I've come to find out that it's explicitly the onClick(this) function that is causing all of the errors. When used with something else, the onClick function works perfectly, but for some reason, the this keyword doesn't appear to actually be sending the reference to the fileObject since all checks show file being undefined when inside of the onClick scope.
Is there something fundamentally wrong about the way I'm trying to do this or am I just missing a step (or adding something that I don't need) that will help get this snippet working.
So you know, your initial problem isn't actually handling the action, but listening to it. click will trigger a synthetic click event, rather than liste for one.
You want ... .element.addEventListener("click", callback); that said, you face a second problem, immediately thereafter.
I will leave my example code as you've written it to not confuse the matter...
But when you see click( ) know that I mean subscribing with addEventListener, if element really does mean a browser DOM element. If it's not a standard browser element, and your own API, then ignore the previous portion, and carry on.
this is dynamically bound at the invocation time of the function (not at definition time).
The nearest function, scoped above, is your callback function that you are passing into .click( ... ).
Which is entirely different than the this which you mean outside of the callback.
Whatever is on the left-hand side of the dot is the this context for the duration of that particular invocation.
Needless to say, click() doesn't know enough to bind the this you mean, to the left-hand side of your callback.
The solution (or one of many) is to use lexical scoping and/or closure to retain the value of the object you mean.
// easy but messier
var fileObject = this;
... .click(function () { onClick(fileObject); });
// Cleaner with thunks:
function clickHandler (onClick, obj) {
return function () { onClick(obj); };
}
... .click(clickHandler(this));
Coming from c++ the way Javascript handles this will seem a little crazy, it looks like here you need to tell the function you've defined what this is - like so:
this.element.click(function() {onClick(this)}.bind(this));
I have plenty of pages on my website with javascript embeded in them.
alert() which is a javascript function has been used in all my scripts atleast once. I want to use custom alert box which will render same in all the browser.
I can define my own function like
function customAlert()
{
// Code goes here.
}
But have to replace alert() withcustomAlert() in all my web pages which is a time consuming process.
Instead can't we just modify native alert function accordingly and it reflects the same as in all browsers.
I think we can't use this
function alert()
{
// Code goes here.
}
because alert is a reserved javascript word for function name.
If there is a better way for implementing the same with different technique, then feel free to answer.
I hate to use jquery or any other frameworks library so please answer regarding pure javascript.
The alert is a property of the global window object, thus you can override it in the following way:
window.alert = function (message){
//do your code
};
and then use it the way you used it before:
alert('hi');
I could really use a second pair of eyes on this. I get the following error:
"Uncaught TypeError: undefined is not a function"
Can anyone see what is wrong with this function because I can't seem to debug
$(function(){
$('#div-id').insertBefore('#sumbit-button');
})();
jQuery already executes the function you pass to it, it does not return a function so you can't call it.
$(function(){
$('#UGInterestedIn').insertBefore('#sumbit-button');
});
There's 2 different things you can mean with this code. Either you're trying to make a function run on DOM ready, which would use the jQuery code:
$(function(){
$('#UGInterestedIn').insertBefore('#sumbit-button');
});
Which is also what aduch said, but you can also be referring to a self-executing anonymous function, which would be this vanilla JS code:
(function(){
$('#UGInterestedIn').insertBefore('#sumbit-button');
})();
The difference is that the first code requires jQuery to be included on the page, and loads the code when the DOM is ready. The second code runs the code immediately, but uses the anonymous function to change the scope of the variables. You're probably trying to do the first thing, but I thought I'd let you know about the second one too.
Sorry to ask a naive question but I'm trying to figure out the best way to structure a bunch of code into something that is easier to manage
I wanted to put events and their responses into 'controllers' for different sections of site. I was looking through the book Javascript Web Applications and saw some promising stuff like this (p5 - my comment for what I thing I understand):
var controller={}; // ok- an object literal
(Controller.users = function($){ // creating an anonymous function; I don't get the dollar sign since it seems to work fine without it
var jtClick= function(){
alert('you clicked on me!');
};
$(function(){
$('#view').on('click',jtClick);
});
})(jQuery);
but I also noticed that this did the same thing:
var controller={};
(Controller.users = function(){
var jtClick= function(){
alert('you clicked on me!');
};
$(function(){
$('#view').on('click',jtClick);
});
})();
So do I need to pass jQuery as part of my anonymous function? Is this changing how scope is going to be handled? I updated the title to remove 'fully' since I don't think I'm getting much of this
thx in advance
This is a self-invoking function and allows you to safely use jQuery with other libraries that use $ as a library object/variable.
$ in the above example is nothing but the jQuery object that is being passed while invoking the function.
I have a coding difficulty which have been asked in this forum before:
Calling a JavaScript function returned from an Ajax response
But I didn't find the answers quite satisfying. To be more precise of the problem I'm dealing, here is the detail:
I dynamically load a document (HTML and javascript) using jquery
var url = 'document.php';
$('#container').load(url);
Example of what the document.php looks like:
<form>
<input name="firstname"></input>
</form>
<script>
function dosomething()
{
console.log($('input[name=firstname]').val());
}
</script>
*The dosomething() function is the one I'd like to call later
And then I want to call the functions from that document.php. Due to my requirement, I don't want to call the function after the documents' loaded, but rather to call it later when I need it. Because it was dynamically loaded, the DOM doesn't recognize the functions. How to properly call this function?
Thank you
the DOM doesn't recognize the functions
This sounds like your other functions are wrapped in $(document).ready() in the remote page. If that is the case they are out of scope for you to call them from code in the main page and you need to move them out of the ready handler to make them globally accessible.
EDIT: Other possibilities
Script tags in head- move to body after html, or use $.getScript in ajax callback to retrieve
I think that you're trying to implement the technique called on-demand javascript (or lazy-loading). In other words, your page should initially load just a small script - but use a bunch of objects and functions, which are available in some other files, but will be loaded when they're required.
If that's the case, I have to warn you: you'll probably need to update your existing code. Instead of just calling some function right as it is, in all gun-blazing glory, you should check for its existence first - and if it's not available, wait for its loading:
if (typeof lazyObjects.someLazyFunction !== 'function') {
lazyLoad('lazyFunction.js');
}
lazyObjects.someLazyFunction();
The key point here is that lazyLoad should be synchronous. In other words, you'll have to wait until the script containing your function is actually loaded. Otherwise someLazyFunction just won't be defined when it's called, even with this sort of checks.
lazyFunction.js, in turn, will contain some code that will alter lazyObjects, adding to them the required method as a property:
// in lazyFunction.js
lazyObjects.someLazyFunction = function() { ... }
While it's technically possible to use global (=window) object for these cases, I usually don't do this - and won't recommend doing it either.
See, it's not that simple. ) I'd recommend reading this article to find out more about this technique - and actually using some established components to implement it in your code (some of them are mentioned in the linked article).