Javascript: Can I avoid closures? - javascript

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?

Related

Missing name after . operator

I'm having problem figuring out, what exactly is going wrong here,
The thing that I understand is this keyword is causing the problem but I can't figure out how and why.
I have tried $(this) and (this)
function makeChoice(){
$(".choices").click(".js-choice", function(){
var choice = this.(".js-choice").val();
});
console.log(choice);
}
I'm creating a quiz app that has 4 options for each question, and for each answer there is a class js-choice and I want the answer from only the button that is clicked currently.
It looks like you've potentially made a syntatical error with trying to create a delegate event handler. If so this can be solved by fixing the binding. And moving the log into the event handler.
function makeChoice(){
$(".choices").on("click", ".js-choice", function(){
var choice = $(this).val();
console.log(choice);
});
}

Hide the password textbox and submit

This is a simple password checking function I messed around with for a little bit. I've tried a lot of different methods (including, but not limited to: .css(), .on('click'), .click(), .animate(), .show(), .hide(), .preventDefault() on the submit), put selectors into variables, moved around all sorts of IDs and $('input[name="s"]') and all sorts of selectors. Not sure if the function won't work, or maybe something else within the script. I've taken the function out of the $(document).ready() tree, and moved it all around inside of it. I'm sure that isn't the problem now, but I'm starting to not be sure about anything at this point.
I'm trying to get the function to hide the password textbox and submit(or is button better?) and show a textarea for news input, with a button to append the update.The appendedTo and .append() section works, but I can't seem to get the passwordcheck function to work. Sometimes it will alert me if it's wrong, but when it's right the if methods don't seem to work. Then I'll change it a few times and the alert will no longer show, nor will the if work any longer.
Any help would be appreciated, and I can provide any code snippets or chunks at request.
Function in question:
function passwordcheck() {
var $newspass = $('#newspass');
var $submitpass = $('#submitpass'); // <--- variables were at one point selectors
var $newssubmit = $('#newssubmit'); // written out, I've changed this a lot
if ($newspass.val() === 'comecorrecT') {
$submitpass.css('display', 'hidden');
$newspass.css('display', 'hidden');
$('#newsinput').css('display', 'block');
$newssubmit.css('display', 'static');
} else {
alert("Try again, please.");
}
};
Rest of the script, for reference:
$(document).ready(function(){
// billboard functions
var $billboard = $('.billboard');
$billboard.mouseenter(function(){
$(this).fadeTo('slow', 0.98);
});
$billboard.mouseleave(function(){
$(this).fadeTo('slow', 0.72);
});
var $learn = $('#learn-more');
$learn.hover(function(){
$(this).fadeTo('slow', 1);
},
function() {
$(this).fadeTo('slow', 0.6);
});
// news and updates/appendedTo
var $submitpass = $('#submitpass');
var $newssubmit = $('#newssubmit');
$submitpass.click(passwordcheck());
$newssubmit.click(function(){
$('#appendedTo').append('<div class="update">'+$('#newsinput').val()+'</div>');
// passwordcheck();
});
});
I've been working with it for a little while now, and I know you guys will have a profound explanation or two.
The way you are doing it now, you are simply passing "undefined" instead of a function (which would be what the passwordcheck function returns) as you are calling the function instead of passing a reference to it in this line:
$submitpass.click(passwordcheck());
Which should be
$submitpass.click(passwordcheck);
In the last block of your code, after
// news and updates/appendedTo
This being said, don't use client side JavaScript for authentication, the password you are checking against is visible for anyone using the site.
Try this:
function passwordcheck() {
var newspass = $('#newspass').val();
var submitpass = $('#submitpass').val();
var newssubmit = $('#newssubmit').val();
if (newspass == 'comecorrecT') {
$('#submitpass').hide();
$('#newspass').hide();
$('#newsinput').show();
} else {
alert("Try again, please.");
}
}

JS-Error: function is not known ("is not a function")

Other people had this problem also, but I was not able to transfer the answers to my problem. So I just ask :-)
I got this code, using a star-rating-plugin ("rateit"):
<div class="rateit"></div>
Now I want to call a function after clicking on the div. When I just use
$(document).on('rated', '.rateit', function() { alert("aha"); });
this works, I get the alert. But when I call a function of the rateit-plugin with
$(document).on('rated', '.rateit', function() { ratingHelper.submit($(this).rateit('value'));
});
I get the error ".rateit is not a function". I get the same error when using
$('.rateit').bind('rated', function() { ratingHelper.submit($(this).rateit('value')); });
The function to call looks like
var ratingHelper = function(){
};
ratingHelper.prototype = {
submit: function(v){
...
Well I am new to JS/jQuery and totally helpless. I would appreciate any help very much. Thanks in advance!
EDIT
Oh man ... I had the jquery.js imported TWICE :-( sorry for bothering you and thanks for your help!!
$(document).on('event', 'element', callback);
event: name of event run
element: elements of trigger
callback: function run after trigger
In your case -> '.rateid' is class name in DOM, and in this -
$('.rateit').bind('rated', function() {}); you not pointing at the item

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.

Click handler event listene

I've been searching all over the place and even if I have found the answer, it has not been delivered in terms I can understand. I'm playing around with this code on jsfiddle, trying to understand why this click handler is not working. I apologize if this is a useless post, just trying to make sense of it all. If anyone knows any good tutorials on how JavaScript code is rendered and how functions pass objects etc.. please, do link me! I've read the basics of how to write functions etc.. but understanding whats going on when the code is parsed, to me, is quite a different thing.
Here is the code I'm trying to get to work:
http://jsfiddle.net/UumUP/3144/
// Function to change the content of t2
function modifyText(evt) {
var thing = evt.target;
thing.firstChild.nodeValue = "four";
}
// add event listener to t
var el = document.getElementsByTagName("td");
for(i = 0; i < el.length; i++) {
el[i].addEventListener("click", modifyText(evt), false);
}
You are calling the function and passing the result of that call, rather than passing a reference of the function, do this instead:
el[i].addEventListener("click", modifyText, false);
http://jsfiddle.net/UumUP/3145/
el[i].addEventListener("click", modifyText(evt), false);
supposed to be
el[i].addEventListener("click", modifyText, false);
Check Fiddle

Categories