How to change variables within the same function. Javascript -
i want change input value clicking on div + adding css effect . issue got 10 divs. can making function each 1 of them i´m pretty sure there better way without repeating code. i´m starting @ this, great if help.
i got input , few divs numbers:
<input type="text" id="screen" dir="rtl"/> <div class="key" id="tres">3</div> <div class="key" id="dos">2</div> <div class="key" id="uno">1</div> ...
and function:
var screen = document.getelementbyid("screen"); var tres = document.getelementbyid("tres"); var dos = document.getelementbyid("dos"); var uno = document.getelementbyid("uno"); uno.onclick=function () { screen.value+=uno.innerhtml; uno.style.boxshadow="none"; settimeout(function() { uno.style.boxshadow="0px 0px 5px 2px rgba(0, 0, 0, 0.2), inset 0px 0px 1px 1px rgba(0, 0, 0, 0.2)"; }, 220); }
now want use same ".onclick" function on every single div, not in newbie way (re writting function , changing variables) in practical one. i've been trying "classname" instead of "id". i´ve attempted ".replace" trying replace value names. , im trying this:
var hell=["uno","dos","tres"]; var screen = document.getelementbyid("screen"); (var = 0; < hell.length; i++) { document.getelementbyid(hell[i]).onclick=function to() { screen.value+=document.getelementbyid(hell[i]).innerhtml; } }
i barely know i´m doing little bit of enlightenment grateful (avoiding jquery if possible).
thanks lot! (sorry bad english)
you can select elements class name, attach eventlistener each of elements, , you'll wanted.
var screen = document.getelementbyid("screen"); var elements = array.from(document.getelementsbyclassname('key')); elements.foreach(el => el.addeventlistener('click', fn)); function fn(e) { screen.value = (parseint(screen.value, 10) || 0) + parseint(e.target.innertext, 10); elements.foreach(el => el.style.boxshadow = "none"); settimeout(function() { e.target.style.boxshadow = "0px 0px 5px 2px rgba(0, 0, 0, 0.2), inset 0px 0px 1px 1px rgba(0, 0, 0, 0.2)"; }, 220); }
<input type="text" id="screen" dir="rtl" /> <div class="key" id="tres">3</div> <div class="key" id="dos">2</div> <div class="key" id="uno">1</div>
Comments
Post a Comment