Generate a function for an event - javascript

I want to generate functions for an event by using a loop. Surely in the example below, when pressing the button, it will gives the value 100 and not 1.
<body>
<button id="b1">klickMeNow</button>
<script>
var i=1;
document.getElementById("b1").addEventListener("click", function() { alert(i);}, false);
var i=100;
</script>
</body>
I came up with this solution using a generate function:
<button id="b1">klickMeNow</button>
<script>
var i=1;
document.getElementById("b1").addEventListener("click", generate(i), false);
var i=100;
function generate(i1) {
f = function () {alert(i1);};
return f;
}
</script>
Is there a more elegant solution without writing a generate function?

Are you looking to for a simple counting function?
var count = (function() {
var c = 0;
return function() {
return ++c;
}
}());
document.getElementById('b1').onclick = function() {
alert(count());
}
<button id="b1">Click Me</button>

Oh sorry for the confusion.
If you run the first snippet it gives 100 as a result, but I want that it prints 1, the actual value when I bind the function.

Related

How to apply keyup() function to different DOM element with different input correctly?

I'm trying to limit different min and max input of the day, month and year input of date of birth. However it seems there's something wrong with "this" in the function. May I know what is the correct and good way to write this function? I tried arrow function but it does not work. Should I use bind? Thank you so much!
$(document).ready(function () {
var minMonth = 1;
var maxMonth = 12;
var minDay=1;
var maxDay=31;
var minYear=1900;
var maxYear=2019;
function minMaxDob(minDob, maxDob){
if($(this).val() > maxDob){
$(this).val(maxDob);
}
if($(this).val() < minDob){
$(this).val(minDob);
}
}
$("#dob_month").keyup(function(){
minMaxDob(minMonth,maxMonth);
});
$("#dob_day").keyup(function(){
minMaxDob(minDay,maxDay);
});
$("#dob_year").keyup(function(){
minMaxDob(minYear,maxYear);
});
});
You have to pass the jQuery object to the minMaxDob like the following, you have to do this because "this" refers to the currently executing function, since you are calling a helper function "this" no longer refers to the DOM object, but to the function minMaxDob:
$(document).ready(function () {
var minMonth = 1;
var maxMonth = 12;
var minDay=1;
var maxDay=31;
var minYear=1900;
var maxYear=2019;
function minMaxDob(jqObj, minDob, maxDob){
if(jqObj.val() > maxDob){
jqObj.val(maxDob);
}
if(jqObj.val() < minDob){
jqObj.val(minDob);
}
}
$("#dob_month").keyup(function(){
minMaxDob($(this),minMonth,maxMonth);
});
$("#dob_day").keyup(function(){
minMaxDob($(this),minDay,maxDay);
});
$("#dob_year").keyup(function(){
minMaxDob($(this),minYear,maxYear);
});
});
you forget to pass object.
Every time you call function inside a function, function will read only passed data, not variables or object on top.
Example:
function run(){
x=2;
y=3;
check(x);
//or
check2(x,y);
}
function check(x){
if(x<y){
console.log('in that example you will have a error becouse you are not passing 2nd val')
}
}
function check2(x,y){
if(x<y){
console.log('Yes, x is smaller than Y, we send all necessary data')
}
}
Simple ad 'this' and reconstruct your main function.
Your script below with snippet
$(document).ready(function () {
var minMonth = 1;
var maxMonth = 12;
var minDay=1;
var maxDay=31;
var minYear=1900;
var maxYear=2019;
function minMaxDob(minDob, maxDob,el){
if(el.val()> maxDob){
el.val(maxDob);
}
if(el.val() < minDob){
el.val(minDob);
}
}
$("#dob_month").keyup(function(){
minMaxDob(minMonth,maxMonth,$(this));
});
$("#dob_day").keyup(function(){
minMaxDob(minDay,maxDay,$(this));
});
$("#dob_year").keyup(function(){
minMaxDob(minYear,maxYear,$(this));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='dob_month' type='text'>

Javascript output during function loop

Is there an easy way to output content when inside a Javascript loop, rather than have it display on screen after the loop has completed.
Code e.g:
var c = 0;
while (c <=1000 ){ //100000
run();
c++;
}
function run() {
console.log(c);
$('#data').append(c);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<div id="data"></div>
It outputs to console straight away (during loop) but on screen does not.
Hoping someone can assist.
Thanks!
Are you wanting to write it to the webpage?
If so then you can write it to a div using the InnerHTML
document.getElementById("yourDivID").innerHTML = yourString;
Your browser's Javascript engine is too fast thus you cannot see the changes in real time. So set a timer and slow down the process.
Run the below code and see the magic happens...
var c = 0;
$(document).ready(function () {
run();
});
function run() {
var timer = setInterval(function () {
//console.log(c);
$('#data').append(c + "\n");
if (c++ == 1000) {
clearInterval(timer);
}
}, 12); //set time in milliseconds
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data"></div>
These are the changes made to your code :
Removed the while loop and replaced it with setInterval()
Added $(document).ready() function to make sure the run() is executed after the DOM is fully loaded.
Try using clousres and setTimeout:
function run(c) {
console.log(c);
$('#data').append(c + ', ');
}
$(function() {
for (var c = 1; 999 > c; c++) {
(function(c) {
setTimeout(function() {
run(c);
}, 1);
})(c);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data"></div>

Event run before click button

this is my code :
<body>
<button id="mybtn">Click Me!</button>
<script>
document.getElementById("mybtn").onclick = sum(2,5);
function sum(a,b) {
document.getElementById("x").innerHTML = a + b;
}
</script>
</body>
why document show 7 before click button?
what happened there you are executing the function instead of assigning it
here is a solution :
document.getElementById("mybtn").onclick = function(){ sum(2,5) };
In addition to #NetaMeta's answer you can use Function.prototype.bind() method to create new function from sum function and prepend parameters:
document.getElementById("mybtn").onclick = sum.bind(null, 2, 5);

Javascript doesn't seems to be running

Ok, I have been trying to make it work past 30 minutes.
Everything works fine in this jsfiddle :- http://jsfiddle.net/6KT4R/1/
But when I run this on my local wamp server..nothing seems to happen!.
Code :-
<script src="js/jquery-1.8.2.min.js" type="text/javascript">
</script>
<script type="text/javascript">
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
</script>
<input type="text" name="ltc" id="input-ltc">
<input type="text" name="btc" id="input-btc" readonly>
What is possibly wrong here?
Thanks.
The script is executing before the DOM is loaded. Try:
window.onload = function(){
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
}
As m59 suggested there is an improved method of executing the event onload. The following code snippet is preferred:
var funct = function(){
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
}
if (window.attachEvent){
window.attachEvent('onload', funct);
}else{
element.addEventListener('load', funct, false);
}
You're getting your element references before the elements exist on the page. In the jsfiddle, the javascript is executed after the html. You could reproduce this by moving your script tag below the related html. It is best practice to put all script tags just before the end of the body like this:
<script></script>
</body>
Otherwise, you'll need to register an event listener to watch for page load and execute your javascript code then.
window.addEventListener('load', function() {
console.log('loaded!');
});
with jQuery:
$(document).ready(function() {
console.log('loaded!');
});
//this is the jQuery shorthand for the same function above
$(function() {
console.log( "loaded!" );
});

Color-cycling an element not working?

I am a beginner in javascript, can you tell me what's wrong with the below code?
I want this to invoke buttonPressed() when a button gets pressed. From buttonPressed() it should call changeColor1(), changeColor1() should change the text color of a paragraph, and start a timer to invoke changeColor2(). Similarly changeColor2() should also change the color and call changeColor1() once the timer expires.
<html>
<head>
<script type="text/javascript">
function changeColor2()
{
alert("2");
var v = document.getElementById("onet");
v.style.color = rgb(0,255,255); // this statement is not working
var t=setTimeout(changeColor1,3000);
}
function changeColor1()
{
alert("1");
var v = document.getElementById("onet");
v.style.color = rgb(255,255,0); // this statement is not working
var t=setTimeout(changeColor2,3000);
}
function buttonPressed()
{
alert("Hello");
changeColor1();
}
</script>
</head>
<body>
<p id="onet"> Hello how are you? </p>
<form>
<input type="button" value="Display alert box!" onClick="buttonPressed()" />
</form>
</body>
</html>
Do not invoke the function, pass the reference only:
var t=setTimeout(changeColor2,3000);
I think you want style.color not .color.
By the way... please tell us what the code is supposed to actually do and what is wrong initially.
You need to quote style property values-
v.style.color = 'rgb(255,255,0)';
1) I don't like the fact that you have two timeouts set. Just call one function and use a flag to toggle between the two options.
2) The parameter to setTimeout that you want to use is a function pointer (changeColor) not the result of a function call (changeColor())
var flag = false;
var t;
function changeColor()
{
var v = document.getElementById("onet");
if(flag){
v.color = rgb(255,255,0);
} else {
v.color = rgb(0,255,255);
}
flag = !flag;
}
function buttonPressed()
{
alert("Hello");
t=setInterval(changeColor,3000);
}
Not really knowing what it is you're trying to do, I can tell you that your button's onClick handler references a method name that isn't in your code. Judging by the names of your methods, I think you meant to put "buttonClicked" in there.
Nevermind, looks like you changed it while I was typing.
Instead of v.color = rgb(0,255,255); use v.style.color = "#0ff".

Categories