Function runs automatically and can't call Javascript function - javascript

A document contains script
$(document).ready(function() {
$(function reset(){
$("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = [];
console.log('reser was executed!');
});
$("#reset").click(function() {
reset;
/* $("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = []; */
});
});
and in page html
<p>
Reset all
</p>
The function reset executed on page load.
How can I prevent it from executing on page load?
When I press link Reset all the function reset does not work? Why?

Give this a shot
Remove the $( ) around your function. - This is what makes it execute automatically.
Then in the button put ()'s after the name reset() - This is how you call a function in Javascript
$(document).ready(function() {
function reset(){
$("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = [];
console.log('reser was executed!');
};
$("#reset").click(function() {
reset();
/* $("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = []; */
});
});

Remove the $(...) from the function declaration and call reset() like a normal function.
$(document).ready(function() {
function reset(){
$("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = [];
console.log('reser was executed!');
}
$("#reset").click(function() {
reset();
/* $("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = []; */
});
});
You just want it to be a normal function. When you put it in $(...), jQuery thinks it's a function that'll return a set of selectors, so it calls it immediately. You don't want that.

check this
$(document).ready(function() {
function reset(){
$("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = [];
console.log('reser was executed!');
}
$("#reset").click(reset);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Reset all
</p>
There is no need to have an anonymous function in the click event binding,you can directly set to the reset function

Remove "$" before your function and add () for call the function.
function reset(){
};
$("#reset").click(function() {
reset();
});

Related

Function inside event listener triggers only on it's initialization

var init = true;
$('#btn').on('click', delay(function() {
$('#text').append('click');
init = false;
}, 100));
function delay(fn, ms, enabled = true) {
$('#text').append(init);
// if(init) disable delay
let timer = 0;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(fn.bind(this, ...args), ms || 0);
}
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id='btn'> TRIGGER </button>
<div id="text"></div>
Init is a global variable which is meant to be used inside delay function to disable delay (init true/false) only on event listener initialisation.
The problem is that the delay function is triggered only once and ignores the change (to false) of the init variable.
For example, try clicking the trigger button. The init variable value is printed only for the first time.
You are calling the delay function in a wrong way in the click handler. You have to call it like so:
$('#btn').on('click', function () {
delay(function() {
$('#text').append('click');
init = false;
}, 100);
});
You will have to check for the value of init inside the function, like this:
$('#btn').on('click', delay(function() {
if(init) {
$('#text').append('click');
init = false;
}
}, 100));
At the moment I don't know why append is not working but with a little workaround you can obtain what you want. Concatenate the original text and the actual one and use text() to set it again:
var init = true;
$('#btn').on('click', function() {
$('#text').text(init);
setTimeout(myDelay, 5000);
});
function myDelay() {
let originalText = $('#text').text();
init = false;
console.log("init is false");
console.log("original text displayed: " + originalText);
$('#text').text(originalText + " " + init);
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id='btn'> TRIGGER </button>
<div id="text"></div>

How to use callback function under document ready function

I have used this function for form validation. I have used this function without
$ function(document).ready(function(){.............});
Its working well. Now I want to add my code under this
$ function(document).ready(function(){.............});
How could I do that. Thanks.
function myFunction () {
var a = document.getElementById("num").value;
var b = document.getElementById("num2").value;
var msg = "";
if(a==""){
msg+="Please Fill this field.\n";
num.className = "color";
}
if(b==""){
msg+="Please Fill this field.\n";
num2.className = "color";
}
if(msg=="") {
return true;
}
else {
document.getElementById("result").innerHTML="Please fill the user name";
document.getElementById("result2").innerHTML="Please Put your E-mail";
return false;
}
}
$(document).ready(function(){ myFunction(); });

JS function that stops another JS function

I have two JS functions: a load() function that displays a progress bar and a kill () function that stops the execution of the load once the page is loaded.
Now when another page is loaded the progress bar is not displayed, knowing that the load function is called on every page.
Any hints on where the problem might be and if there is a way to fix it.
Here is my code:
<script type="text/javascript">
var count=0;
function load(i) {
j = parseInt(i);
document.getElementById("progressBar").style.display = "block";
count=count+1;
if (document.all) {
document.all.btn1.value=count+'%';
document.all.progressbar.pic1.width=2*count;
}
else {
document.getElementById("pic1").width=2*count;
document.getElementById("bar").width=count+'%';
}
if (count<100) {
setTimeout('load(j)',j);
}
if(count==100) {
document.getElementById("progressBar").style.display = "none";
count=0;
}
}
function kill(){
if (document.applets[0].isActive()) {
document.getElementById("progressBar").style.visibility = "hidden";
}
}
</script>
Thank you in advance !
In load() you're changing display to block, but in kill() you set visibility to hidden; you should set display to none instead, so it can properly be set to block again next time. Read about visibility.
Optimized code:
<script type="text/javascript">
var count = 0,
win = window,
doc = document,
progressBar = doc.getElementById("progressBar"),
t, j;
function load(i) {
j = parseInt(i);
progressBar.style.display = "block";
count++;
// no actual need to check if doc.all is available
// just select through id
doc.getElementById("pic1").style.width = 2*count;
doc.getElementById("bar").style.width = count+'%';
if (count < 100) {
t = win.setTimeout('load(j)',j);
} else {
progressBar.style.display = "none";
win.clearTimeout(t);
count = 0;
}
}
function kill(){
if (doc.applets[0].isActive()) {
progressBar.style.display = "none";
}
}
</script>
If you assign setTimeout to a variable, you can use clearTimeout on it to stop it.
E.g.
set the timeout with
t = setTimeout('load(j)',j);
then stop it with
clearTimeout(t); Let me know if that helps, and makes sense :)

JavaScript: How stop a function which is started with $(function(){})

I created a function and then called this function when the page loads, also I need call same the function, but without it existing twice. I want it to just stop from $(function(){}) and call again when an element is clicked on.
function myfunction(){
console.log('message');
}
$(function(){
myFunction();
$('#id').click(function(){
...some code here ...
myFunction();
});
})
When page is loaded the console gives me: "message" - it's ok, but when click on #id then I get this message twice, if again then 3 times;
Here my code
function select_cta(){
$('.cta-id').click(function(){
console.log('-');
$('.cta-id').removeClass('active');
$(this).addClass('active');
var cta_arr = parseInt($(this).attr('id').replace('cta-button-', ''))-1;
$('.cta-image').fadeOut(300).removeClass('active');
$('#'+$(this).attr('id').replace('cta-button', 'cta-image')).fadeIn(300).addClass('active');
if(cta_data[cta_arr]){
$('.cta-actions #cta_id').val(cta_data[cta_arr].id);
}
else{
$('.cta-actions #cta_id').val('');
};
if(cta_data[cta_arr]){
$('.cta-actions #cta_link').val(cta_data[cta_arr].link);
}
else{
$('.cta-actions #cta_link').val('');
};
});
}
$(function(){
select_cta();
$('.add-new-cta').click(function(){
var new_tab = parseInt($(this).prev().attr('id').replace('cta-button-',''))+1;
$(this).before('<div id="cta-button-'+new_tab+'" class="cta-btn cta-id empty" style="display:none;"><span>'+new_tab+'</span><span class="onair">ON</span></div>');
$('#cta-button-'+new_tab).fadeIn(300);
$('.cta-images').append('<div id="cta-image-'+new_tab+'" class="cta-image " style="display:none"><img src="/assets/images/page/placeholder_cta.gif"></div>');
select_cta();
})
});
Your problem that every call to select_cta adds another handler to each of the elements. They all would be executed when the click event fires. Two solutions:
Unbind the event handlers from all elements before you re-add them. To do so, begin the function select_cta with $('.cta-id').off("click").on("click", function(){…
Better: use event delegation:
jQuery(function($){
function getIdNumber($el) {
return parseInt($el.prop('id').replace(/\D/g, ''), 10);
}
var $active = $('.cta-id.active'),
$activeImg = $('.cta-image.active')
$(document).on("click", '.cta-id', function(e) {
$active.removeClass('active');
$active = $(this).addClass('active');
var num = getIdNumber($active);
$activeImg.fadeOut(300).removeClass('active');
$activeImg = $('#cta-image'+num).fadeIn(300).addClass('active');
var cta_arr = num - 1;
if(cta_arr in cta_data) {
$('#cta_id').val(cta_data[cta_arr].id);
$('#cta_link').val(cta_data[cta_arr].link);
} else {
$('#cta_id').val('');
$('#cta_link').val('');
}
});
$('.add-new-cta').click(function(e) {
var $this = $(this),
new_tab = getIdNumber($this.prev())+1,
new_button = $('<div id="cta-button-'+new_tab+'" class="cta-btn cta-id empty" style="display:none;"><span>'+new_tab+'</span><span class="onair">ON</span></div>');
$this.before(new_button);
new_button.fadeIn(300);
$('.cta-images').append('<div id="cta-image-'+new_tab+'" class="cta-image " style="display:none"><img src="/assets/images/page/placeholder_cta.gif"></div>');
})
});

Assign onchange to an object and pass a parameter

So I have the following JavaScript:
<script language=JavaScript>
function reload(form){
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
function init(){
var form = document.getElementById("myform");
document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;
</script>
But then it keeps on reloading itself constantly. Which is expected. But how can I assign reload and pass a function instance to it?
I could do:
<script language=JavaScript>
function reload(){
var form = document.getElementById("myform");
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
function init(){
document.getElementById("id_profile").onchange = reload;
}
window.onload = init;
</script>
But what if I have more forms? Or I let say I want to reuse reload on multiple pages with different form names.
I would like to avoid setting onchange in the HTML tag though:
onchange="reload(this.form)"
If this is possible at all?
Thanks!
But what if I have more forms?
You can assign the same function to all the profile elements in the forms, and reference the element that received the change event inside the function using this.
<script type="text/javascript">
function reload(){
// In here, "this" is the element that received the event
var val = this.options[ this.options.selectedIndex ].value;
self.location='?profile=' + val ;
}
function init(){
var len = document.forms.length;
while( len-- ) {
document.forms[ len ].profile.onchange = reload;
}
}
window.onload = init;
</script>
You can make a function that returns a function (a closure) for the reload function.
function reload(form){
return function(){
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
}
function init(){
var form = document.getElementById("myform");
document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;

Categories

Resources