Javascript: JSON request works only for the first time - javascript

I have a script which registers a click event to a button.
The function which should be executed when the button is clicked, should make a JSON request to a Quotes API and give my Quote element the random quote.
$("document").ready(function() {
$("#new-quote").on("click", newQuote());
});
function newQuote() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
$("#quote-paragraph").html(a[0].content);
$("#footer").html(a[0].title);
});
}
This is how my code should look like, but I already tried different solutions and to find my error. I added an alert() statement at the end of my function to see if the function gets executed, which it does. Well sometimes. I tried it a couple times and got different results each time I tried it. I am working with codepen.io . Thanks for your help!

On the second line
$("#new-quote").on("click", newQuote());
You're executing the function and assigning its result to the onclick event instead of assigning the function itself. That's why your function executes once, when you do the assignment, and not again, because you didn't actually assign it. Do this:
$("#new-quote").on("click", newQuote);

Related

RemoveEventListener without running function

So I am trying to remove my addEventListener function using the removeEventListener function. I've read alot about it needing to include an handler function, which I have done.
One of the issues is that I am running into is that I would like to remove the eventlistener when I change an input using google's searchbox. Don't mind google but really all what is happening is it is identifying when the input value has changed and providing new results. So a bit of code
var input = document.getElementById('search-input');
var searchBox = new google.maps.places.SearchBox(input);
google.maps.event.addListener(searchBox, 'places_changed', locationChange);
function previousButtonFunction(){
//Does something here and does not return anything. Lets just say it places markers all over the map
}
function locationChange() {
var previousButton = document.getElementById('previous');
previousButton.removeEventListener('click', previousButtonFunction());
previousButton.addEventListener('click', function () { previousButtonFunction()})
};
So this code looks like it doesn't make any sense to you probably, but what I am trying to get is that on the first input it would run the add event listener, and not run the removeEventListener function. Once the value of input has changed, I would like to remove the current listener and re-identify the previousButton with a new addeventlistener.
At the first go, I realize that the function of previousButtonFunction() is run, which I thought that it would only run if there was an identified listener. So the first question is the removeEventListener function supposed to run if the eventlistener wasn't added? Second how can I remove the addEventListener without running the function? Would I need to pass in a tracking identifier such as true => run it/false => don't run?
Thanks any help is greatly appreciated
Don't use ()after the function name. You want to pass only a reference to the function. Putting() after the name calls the function and passed the return value. This is a very common mistake.
Change this:
previousButton.removeEventListener('click', previousButtonFunction());
to this:
previousButton.removeEventListener('click', previousButtonFunction);
The same goes for .addEventListener(). Don't put () after the function name unless the function returns another function that you want to be the listener.
FYI, it's a little unclear why you're attempting to remove and then add back the same exactly same listener function. Unless there are multiple listeners on that object and you're trying to change the order of listeners, this is essentially a noop.

addEventListener("click",...) firing immediately [duplicate]

This question already has answers here:
addEventListener calls the function without me even asking it to
(5 answers)
Closed 4 years ago.
I'm trying to create some appropriately-placed instructional tooltips that users click through to understand how the site interface works. Each tooltip has a "next" link that toggles the visibility of the previous and next tooltips by modifying the classes (and hence, css).
Here's some simplified code that is supposed to do this:
function displayTooltip(t){
//...some code to determine the tooltip IDs "next" and "previous"
document.getElementById(previous).className = "tooltip invisibleTooltip";
document.getElementById(next).className = "tooltip";
}
document.getElementById("tooltip-link1").addEventListener("click", displayTooltip(2));
displayTooltip is called immediately (and correctly toggles the class) when I paste this code into the console (or on page load). If I replace displayTooltip with an alert(), it fires when I click, as anticipated. What am I doing wrong?
When you are binding event you are calling the function document.getElementById("tooltip-link1").addEventListener("click",displayTooltip(2));
You need to pass reference to the function.
Change to below
document.getElementById("tooltip-link1").addEventListener("click", function(){
displayTooltip(2)
});
When you write functionName followed by (), it will call function. If you wish to assign function to a handler, you should do
document.getElementById("tooltip-link1").addEventListener("click", displayTooltip);
Now if you wish to pass parameter to this function, you can either wrap it inside a function like
document.getElementById("tooltip-link1")
.addEventListener("click", function(){displayTooltip(2)});
Or you can use .bind()
document.getElementById("tooltip-link1")
.addEventListener("click", displayTooltip.bind(this, 2));
You need to call this method as a callback. Since you are calling it as displayTooltip(2) you are ultimately calling the function at that line.
What you need to do is to bind a callback rather than calling at that line.
Something like
.addEventListener('event', function()
{ displayTooltip(2) }
Hope this be of some help
Happy Learning

Prototype function creating elements and using inheritance invoked on load instead of on click

I apologize if the following are stupid questions, this is my first time trying something with OO JS which goes beyond the very basic tutorials out there.
If I get to understand the following questions, it would constitute something like a person breakthrough:-)
Basically, I want to create an element- a div with a background pic- on click and append it to the button.(Later on i want to create an additional button which will replace the above pic with another one).
The pictures are stored in an Array.
If i run this with the commented out lines 37-57, it all works, but i do not want to write that function every time to create the next element.
So I have created the function object "Nation"(lines 4 to 30) and want to pass 2 arguments on call, "land"(name of nation) and "imageIndex"(index of picture in the array).
Here is where the problems start. I want to call new Nation on click(line, but it is executed straight on page load instead. How to fix that?
And I have not passed the second argument now, as I could not figure out how to do it, so I just used line 13 to set the BG pic. But the goal would be to set the BG pic by passing a second argument to the function.
var croats = new Nation("croatia");
document.getElementById("newDom")
.addEventListener("click", croats.create("croatia"));
That is the event handling and the code is here:
http://codepen.io/damianocel/pen/gPggLB
Thank you very much.
You should simply pass a function as 2nd argument of the addEventListener:
document.getElementById("newDom").addEventListener("click", function () {
croats.create("croatia")
});
See for example: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Example
As your code is currently set, it executes croats.create() when attaching the listener, instead of storing a reference to a function (called "listener" or "callback") to be executed when the event occurs.
Updated CodePen: http://codepen.io/anon/pen/KVqgdP

If statement and .click function

I have been making a videogame with javascript. However, there is just one thing that I don't understand.
if (!user.hasOwnProperty('firstName')) {
$('#inputSubmit').click(function () {
user.firstName = getInput();
addText_1("Good, now type your character's last name");
});
};
this statement will keep executing. Basically the condition is that the user does't have a first name property and the function will add the first name on the click of submit. However, you can keep pressing the submit button and it will keep adding the text.
$('#inputSubmit').click(function() {
if(!user.hasOwnProperty('firstName')) {
user.firstName = getInput();
addText_1('hello');
};
});
However, this works. It only does it once. Could someone explain the principle that I am not understanding?
Thank you very much!
You attach a click event to #inputSubmit. This callback ignores the surrounding if statement. In your second sample code, if is inside the callback function.
in first code "hasOwnProperty" checked in outer scope of function() but in second code the condition checked in scope of function

about javascript event handler, it works weird

I am a beginner in javascript. and have no experience in programming, at all.
So I'd like you to be generous to beginner.
And here is my question.
I'm trying to code javascript unobtrusively.
So I put in all of my js codes into external js file. for example : test.js
and deleted these codes. to do unobtrusive js coding. for example :
and I tried to use these 2 methods :
variable.onclick=test(arg1, arg2);
variable.addEventListener('click',test(arg1, arg2),true);
but these triggers didn't work.
to put it delicately, function test(arg1, arg2) worked right after dom loding finished. regardless of activating 'click' trigger.
So I spent several hours solving this problem, and finally got a solution. this is it.
variable.onclick = function(){
variable.addEventListener('click',test('arg1','arg2'),true);
}
I wanna know why first two methods didn't work, and why that solution works well.
I solved the problem, but don't know why, and how...
In JavaScript, when you reference a function by name and follow that reference by a parenthesized list of arguments, that means that you want to call the function, right then and there. Thus a statement like
variable.onclick=test(arg1, arg2);
will assign to the "onclick" property the value obtained by calling the "test" function. In other words that statement means
Please call the function "test" passing it "arg1" and "arg2", and assign whatever it returns to the "onclick" property of the object referenced by "variable".
An event handler must be a function, however, and your "test" handler probably returns either nothing, or something that's not a function. So it didn't work.
Your solution, however, is also incorrect. You're successfully assigning a function to the handler property, but your function is itself installing another event handler. There's no reason to do that here, and in general setting up event handlers from within other event handlers is a suspicious practice. All you need is:
variable.onclick = function() { test(arg1, arg2); };
variable.onclick requires a function declaration by design. In your case you could have just done
variable.onclick = function(){
test(arg1,arg2);
};
The way you did it won't work because you're not giving the click handler any instructions. The corrections I have made say that when the variable (the one with the click handler attached) is clicked trigger this function that will in turn trigger the test function.
Same thing goes for the second one
variable.addEventListener('click', function(){
test(arg1,arg2);
});
This works again because you are saying when this variable is clicked run the function that will trigger the test function.
Basically you are trying to assign the result of running a function, the test function as a task for the click handler to run. This won't work except maybe your test function returns a function that contains code that you want to run when the click event is triggered. Hope this helps.

Categories