JavaScript - Define function without calling it? - javascript

I feel so so stupid for forgetting this, but I've been out of practice for a minute, and I'm drawing a blank.
Why is slideDown being called onload rather than when the click is handled?
function buttonClicked(buttonNumber) {
$contentBox.slideDown("slow");
};
$button1.click = buttonClicked(1);

You would want to structure it as
$button1.click(function() {
buttonClicked(1);
});
This will make it fire when $button1 is clicked.

Try this:
$button1.click(function() {
buttonClicked(1);
});
See documentation at api.jquery.com

Related

addEventListener("touchstart") doesn’t work on phones [duplicate]

I don't know what I am doing wrong but here is an example of what I am doing and it doesn't seem to work.
someDom.addEventListener('mousemove',function(ev) {self.onInputMove(ev)},false);
someDom.removeEventListener('mousemove',self.onInputMove);
The removeEventListener code is executed but it just doesn't remove the 'mousemove' listener
removeEventListener removes the listener that exactly matches the function that was added.
In this case, the function that addEventListener added was:
var some_func = function(ev) {
self.onInputMove(ev);
};
Store a reference to the actual function and you'll be good. So for example, the following should work:
someDom.addEventListener('mousemove',self.onInputMove,false);
someDom.removeEventListener('mousemove',self.onInputMove,false);
onInputMove is not an event-callback method. So you need to do something like:
var event = function(ev) {self.onInputMove(ev)};
someDom.addEventListener('mousemove', event,false);
someDom.removeEventListener('mousemove', event, false);
Why make it yourself so hard, just use the following to bind an event to an element:
element.onmousemove = function(e) {
// Some code here...
alert("Mouse moved!");
};
Now, when you want to remove the event, just do this:
element.onmousemove = null;
Done!
Hope this helps you guys out!
This page comes first on searching this/such issue on Google. So apart from answers already mentioned, here is one more interesting fact for future:
Leaving out the third optional variable in addEventListener() for useCapture/useBubble (as it defaults to false) does create some issue while removing the same eventlistener with same callback name. I faced this issue while working on chrome. Cant say about other browsers.
So do mention the third variable explicitly as "false".

Set delay or timeout before initializing

I'm working with a script that needs to delay (or have a setTimeout) before any animation loads or initializes, but can't seem to figure out where to put it.
As for delay, if I'm not mistaken, this is used mainly with jquery...So for example: $('id or class here').delay(2000); ...Correct?
As for the setTimeout, if I'm not mistaken, it would be with javascript correct? If so, wouldn't it look something similar to this: setTimeout(function () {function_name},2000); or a slightly different variation of that?
Regardless of these two approaches and trying to add it where I think it should go (using either variations mentioned above), for some reason it just doesn't work right. The console isn't really helping either to check for errors.
In a nutshell, I'm trying to set a delay of 2s (2000ms) before anything starts or initializes.
JS CODE (Where I believe the issue lies):
$(document).ready(function() {
// Additional code here...
// start
BG.init();
// Additional code here...
}
});
Where you have this:
$(document).ready(function() {
Put this:
$(document).ready(function() {
setTimeout(function() {
And then where you have this:
});
// wrapper for background animation functionality
var BG = {
Put this:
}, 2000);
});
// wrapper for background animation functionality
var BG = {
And then, if you don't want to incur the wrath of everyone in the world, indent the stuff inside that new function we just created by one more level. 'Cause indentation is the stuff of life.
There's a lot of 'useless' code for us to help you. Next time share only on a need-to-know bases :)
I've edited your $document.ready block to include the timeout, have a look-see:
$(document).ready(function() {
function initiationProcess() {
// setup logo image
BG.logo = new Image();
BG.logo.onload = function() {
BG.logo_loaded = true;
BG.showLogo();
}
// /../ more code /../
// wire ticker listener
Ticker.addListener(BG.tick);
// start
BG.init();
// /../ more code /../
}
setTimeout(initiationProcess, 2000);
});
Edit:
I'd also like to note that it's considered bad practise (not to mention that it might result in buggy code) to only partly use semicolons in your script file. There's points and counterpoints to using semicolons, but pick a standard and stick to it!

Can't listen to global event in jQuery

Another question on stackoverflow pointed out that it should be possible to trigger an event on all listning objects using:
$.event.trigger('customEvent');
However this does not seem to work for me in an example like:
$('body').bind('customEvent', function(){ alert('Working!'); });
Am I doing something completely wrong, or has this great functionality been disabled?
It looks like that functionality has been removed. Browsing through the tags I managed to find this TODO in v1.8b1:
// TODO: Stop taunting the data cache; remove global events and always attach to document
And it was removed as of v1.9.0.
There is nothing stopping you from implementing it based on the old source code here (v1.6.2), but it looks like it was doing naughty things talking to jQuery.cache so it's probably best to live without it or come up with another solution.
$('*').trigger('customEvent');
Perhaps? (jsFiddle)
Or a more efficient approach of keeping track of each subscription and calling .trigger() on that.
jsFiddle
var customSubs;
$.fn.subscribeCustom = function (fn) {
this.on('customEvent', fn);
if (!customSubs)
customSubs = this;
else
customSubs = customSubs.add(this);
};
$('span').subscribeCustom(function () {
alert('span!');
});
$('div').subscribeCustom(function () {
alert('div!');
});
customSubs.trigger('customEvent');

JavaScript (jquery) - Scope issue in click event

I know this subject has been already discussed in similar topics, but none of the solutions I could find can help me understand the issue I have.
Here is my simplified class and its the usual was I define them.
BottomNav = function() {
this.init();
}
$.extend(BottomNav.prototype, {
init: function(){
this.insue = false;
$(".up").click($.proxy(function () {
var thisinuse = this.inuse;
if(this.inuse===false) {
this.inuse = true;
this.moveSlider('up');
}
},this));
},
moveSlider: function(d){
//some instructions
alert('move slider');
}
});
$(document).ready(function() {
new BottomNav();
});
In FireBug on the breakpoint inside the click event this.inuse is undefined! (this is my problem), my scope looks good on the watch (right panel of firebug), this.insue is false as it should be - sorry I cannot post images yet!
I would be grateful of someone might help identifying this very strange behavior.
I tried some staff like putting the click event definition inside another function but it does not work either. I tried different ways of bindings and it does not work too.
However the below example is working on a number of other classes I made. I could access class scope from events, effects.
It's just a typo:
this.insue = false;
Change insue to inuse and the property will be there :-)
Apart from that, the variable thisinuse is quite superfluous in here. And change the condition to if(! this.inuse) instead of comparing to booleans…
this.inuse can be assigned to a variable out side your click event handler and use the variable inside the handler.

Javascript: Can I avoid closures?

I am trying to make an website. I am putting addEventListener to more elements in a function called more times:
idImag = 0;
function function1()
{
//do something
function2()
}
function function2()
{
//do something
document.getElementById("holder" + idImag).addEventListener('mouseover',function(){
idImag++;
alert('It works');
}
function3(event)
{
alert(3);
}
function1();
function1();
<div id="holder0">Dog</div>
<div id="holder1">Chicken</div>
<div id="holder2">Cow</div>
But there is a problem: Only the last element gets the event listener... the others do nothing after putting the mouse over it.
Then I've googled a little and found out about closures and how variables are kept even after function returned... I didn't understand everything, but I just want to find out how to put the event listeners in function2. Can you help me?
Probably you noticed: I am a newbie. Sorry if the question is stupid or if it has no sense. If you need more details, I will put my whole code, but it has variables and comments in Romanian, so I am not sure if you will understand it. Sorry for my bad English and thank you in advance.
Why not a for loop?
function function3 (event) {
alert(3);
}
for (var idImag = 0; i< numberOfHolders; i++) {
//do something1
//do something2
document.getElementById("holder" + idImag).addEventListener('mouseover',function3);
}
It looks like you just care about the image id, which is available through the id attribute of the element.
Thus you can do:
document.getElementById("holder" + idImag).addEventListener(
'mouseover',
function(){
var id = this.id;
/* Then strip off "holder" from the front of that string */
}
);
This looks correct, in that it will call document.getElementById("holder0").addEventListener(…), then it will call document.getElementById("holder1").addEventListener(…). Closures aren't your problem there.
You can verify this by, eg, using console.log to log the element that you're adding the event listener to (you'll need Firebug installed, or Chrome's developer console open).
Maybe paste the code to http://jsfiddle.net/ so we can try it?

Categories