Function doesn't run when I click on the button - javascript

So I have a simple JQuery code:
$(function () {
var podatoci;
var i;
$(".front").on("load", init());
$("#remove").on("click", toggleRemove());
function init() {
load();
}
function load() {
$.get("data.json", function (data, status) {
podatoci = data;
fill();
})
}
function toggleRemove() {
console.log("Yes");
$(".likse-dislikes").toggle();
}
function fill() {
for (i = 0; i < podatoci.length; i++) {
$("#container").append("<div class='wrap'><img class='img' src='"+podatoci[i].url+"'/><div class='likes-dislikes'><img class='like' src='sources/like.png'/><img class='dislike' src='sources/dislike.png'/></div></div>");
}
}
});
When I click on the button with ID: remove it runs the toggleRemove() function.
However when I run the web page and when I got to to the console when I click on the button the function doesn't run, instead it does Console.log("OK") only once presumably when the page is loaded. Can anyone please explain where is the problem and how do I fix it?
Thank you in advance!

This doesn't do what you think it does:
$("#remove").on("click", toggleRemove());
This executes toggleRemove once, when the page loads, and sets the handler to the result of that function. (Which is undefined because the function doesn't return anything.)
You want to set the handler to the function itself, not the result of the function:
$("#remove").on("click", toggleRemove);
Additionally, if your element is being added to the page after this code executes (we don't know, though the code shown implies some dynamic elements being added) then you'd need to delegate the event:
$(document).on("click", "#remove", toggleRemove);

You spelled the class name incorrectly on your remove function.
$(".likse-dislikes").toggle();
Change it to
$(".likes-dislikes").toggle();

As I can see here $(".front").on("load", init()); $("#remove").on("click", toggleRemove()); you call your call back in time when you register event listener. Try this: $(".front").on("load", init); $("#remove").on("click", toggleRemove);

You could use $scope.apply(handler)
$scope.apply(function () {
// Angular is now aware that something might of changed
$scope.changeThisForMe = true;
});

Related

Stop jquery function from automatically being called

I'm sure this is very simple, but I can't seem to find the answer.
I have a RoR app, and in my application.js file I want to call a function from within a function.
application.js:
jQuery(function_1($) {
$("#select_box").change(function() { ....
....
function_2 ();
return false;
});
jQuery(function_2 () {
...
return false;
);
function 1 is triggered when a select box is changed and works correctly. The issue is that function 2 is executed as soon as a new page is loaded. I only want function 2 to be called from within function 1.
How can I do that?
The problem is that when you put code inside of a block like this:
jQuery(function() {
$("#select_box").change(function() {
function_2();
return false;
});
});
The code is automatically executed. This is equivalent to
$(function() {
});
or
$(document).ready(function() {
});
Which should give you an idea of why function_2 is being invoked on page load. To remedy this, just define the function like this:
jQuery(function() {
var function_2 = function() {
return false;
};
$("#select_box").change(function() {
function_2();
return false;
});
});
See jQuery docs: http://learn.jquery.com/using-jquery-core/document-ready/
If you're using the asset pipeline, you shouldn't have javascript functions in application.js at all, it should just be a manifest. So, assuming you've disabled the asset pipeline, I think you just need to change how you define function_2. Try this:
var function_2 = function () {
...
return false;
};
$("#select_box").change(function() {
....
function_2 ();
return false;
});
function function_2 () {
...
return false;
}
Your question says:
function 1 is triggered when a select box is changed and works correctly. The issue is that function 2 is executed as soon as a new page is loaded. I only want function 2 to be called from within function 1.
$(document).on("change","#select_box",function(e) {
// used on function to incorporate for turbolinks
// your code
// to trigger your function1 when select box is changed
function1 ();
e.preventDefault();
});
function function1(){
//your code
// to trigger your function2 inside function1
function2();
}
function function2(){
//your code
}

How can i add $(document).ready(function(){}) after a function in java script

What I want to do is I have a code like below :
$(document).ready(
function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage + '"]').closest('li').addClass('active');
}
)
And now I want to add this code to add and get work with other code. I need to add this code after this one:
function () {
/* If there are forms, make all the submit buttons in the page appear
disabled and prevent them to be submitted again to avoid accidental
double clicking. See Issue 980. */
jQuery(function() {
/* Delegate the function to document so it's likely to be the last event
in the queue because of event bubbling. */
jQuery(document).delegate("form", "submit", function (e) {
var form = jQuery(this);
if (form.hasClass("form_disabled")) {
e.preventDefault();
return false;
}
else {
form
.addClass("form_disabled")
.find(":submit")
.addClass("disabled");
}
// Reactivate the forms and their buttons after 3 secs as a fallback.
setTimeout(function () {
form
.removeClass("form_disabled")
.find(":submit")
.removeClass("disabled");
}, 3000);
});
});
}
How can I get this done. Please help me out to solve this problem.
You can create document.ready() anywhere in script. It is not necessary all of your code should be in ready function.
You can create instance variable for function and call it where you need:
$(document).ready(
var myFunc = function(){
var currentPage = window.location.pathname;
//other code
}
...
//and invoke it where you need
myFunc();
)
First, name the long function in your code section, for example, launchFormControls(). And then define the function outside of the document ready event. A good practice would be to do so and keep the ready event body clean.
For example:
function launchFormControls() {
//function code
}
Or, in other syntax:
var launchFormControls = function() {
//function code
}
Second, call your function from within the document ready event. Your function will be defined and able to call once the document is loaded. This code can be placed at the top or bottom of your javascript section or file.
For example:
$(document).ready(function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage+'"]').closest('li').addClass('active');
launchFormControls();
});

Simple Javascript Calling function not working/don't know how to get it to work

I'm trying to call a function and not the alert and I thought it was as easy as just doing something like this: FunctionsName(); and delete the alert(''); but it's not working for me :(
Can someone please look at the code I have below and tell me what is wrong ?
Thank you so much!!
<script type="text/javascript">
var comper;
function checkComper() {
var onResponse = function(comperNow) {
if (comper === undefined) {
comper = comperNow;
return;
}
if (comper !== comperNow) {
// show a message to the visitor
alert("New Info Added"); // <--*** I WANT TO TAKE THIS OUT AND CALL $("#append").click(function(e)
comper = comperNow;
}
};
$.get('getlastupdate.php', onResponse);
}
var tid = setInterval(checkComper, 2000);
$(function() {
var $table = $("table.tablesorter");
$("#append").click(function(e) {
e.preventDefault();
$.get('updatetable.php', function(data)
{
$table
.find('tbody')
.html('')
.append(data);
$table.trigger("update", [true]);
});
});
/*........ and so on.... */
</script>
What about changin that :
alert("New Info Added");
to that :
$('#append').trigger('click');
It will simulate a click and trigger the function.
One thing important to distinguish:
alert("New Info Added") is a function. Actually, alert() is a function, being passed the parameter "New Info Added".
$('#append').click(function(e) { is not a function, at least, not in the same way. $('#append') is a jQuery selector function, which selects all elements with an id of "append". $('#append').click() is a function that sets a click event on all elements returned in the selector.
What the whole syntax of $('#append').click(function(e) { means is on its own a syntax error. What you're doing is telling the elements found in the selector what their click function should be. But the function(e) { says that it's the start of the code of the function. That line of code isn't complete until the ending }) - the } closing the function declaration and the ) closing the call to click.
So, you can't simply replace alert("New Info Added"), which is a complete function call, with $('#append').click(function(e) {, because it's a syntax error - you haven't completed the function(e) declaration, nor the click function call. You can trigger the click function, as Karl's answer told you. Or, you can use the shortcut:
$('#append').click()
Note that this is a full proper sentence, and can therefore replace the alert.

Trouble calling JavaScript function on page load

I have a javascript function that i have named refreshProjects(), what it does is filter a dropdownlist depending on what was selected in a previous dropdownlist. But i need to also filter my list direcktly after the page has finishd loading.
I have tried using the code window.onload = refreshProjects(id) with no sucsses, but onload workes when i use window.onload = alert('This page has finished loading!'), so i know that part off the script works. So how do i call a javascript function on load, i thought that it would be simple but evrything i tried have failed.
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
window.onload = refreshProjects(id); <-- Problem
$("#ddCustomers").change(function () {
refreshProjects($(this).val());
});
function refreshProjects(id) {
var projects = $("#ddProjects");
$.get('#Url.Action("FilterProjects","TimeEntry")', { customerId: id },
function (result) {
// clear the dropdown
projects.empty();
//Add a deafult "null" value
$("#ddProjects").get(0).options[0] = new Option("[ - No project - ]", "-1");
// rebuild the dropdown
$.each(result, function (i, e) {
projects.append($('<option/>').text(e.Text).val(e.Value));
});
});
}</script>
}
This is for MVC 4.5.
Try changing window.onload = refreshProjects(id); to:
window.onload = function() { refreshProjects($("#ddCustomers").val()); };
Onload expects a callback function. You were directly executing refreshProjects() and setting the return value as the onload.
But since you seem to be using jQUery, you could do the following:
$(function() {
refreshProjects($("#ddCustomers").val());
});
This will execute refreshProjects when the document is ready (which actually is before window load).
You can also try to use the following:
$(document).ready(function () {
refreshProjects(id);
});
This should work aswell if you are using jQuery.

jQuery: Call a function twice

I'm trying to run a function twice. Once when the page loads, and then again on click. Not sure what I'm doing wrong. Here is my code:
$('div').each(function truncate() {
$(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
});
$('.truncate').click(function() {
if ($(this).parent().hasClass('closed')) {
$(this).parent().removeClass('closed').addClass('open').children().show();
}
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed');
$('div').truncate();
$(this).show();
}
});
The problem is on line 13 where I call the truncate(); function a second time. Any idea why it's not working?
Edit jsFiddle here: http://jsfiddle.net/g6PLu/
That's a named function literal.
The name is only visible within the scope of the function.
Therefore, truncate doesn't exist outside of the handler.
Instead, create a normal function and pass it to each():
function truncate() { ...}
$('div').each(truncate);
What's the error message do you get?
You should create function and then call it as per requirement
Define the function
function truncate(){
$('div').each(function(){
});
}
Then call the function
truncate();
Another approach is to establish, then trigger, a custom event :
$('div').on('truncate', function() {
$(this).......;
}).trigger('truncate');
Then, wherever else you need the same action, trigger the event again.
To truncate all divs :
$('div').trigger('truncate');
Similarly you can truncate just one particular div :
$('div#myDiv').trigger('truncate');
The only prerequisite is that the custom event handler has been attached, so ...
$('p').trigger('truncate');
would do nothing because a truncate handler has not been established for p elements.
I know there's already an accepted answer, but I think the best solution would be a plugin http://jsfiddle.net/g6PLu/13/ It seems to be in the spirit of what the OP wants (to be able to call $('div').truncate). And makes for much cleaner code
(function($) {
$.fn.truncate = function() {
this.addClass('closed').children(":not('.truncate')").hide().slice(0,2).show();
};
$.fn.untruncate = function() {
this.removeClass('closed').children().show();
};
})(jQuery);
$('div').truncate();
$('.truncate').click(function() {
var $parent = $(this).parent();
if ($parent.hasClass('closed')) {
$parent.untruncate();
} else {
$parent.truncate();
}
});

Categories