Skip to content

Instantly share code, notes, and snippets.

@ArunHub
Last active July 7, 2018 09:44
Show Gist options
  • Save ArunHub/dfeccbdb1bd7bee834ce70abd19f3512 to your computer and use it in GitHub Desktop.
Save ArunHub/dfeccbdb1bd7bee834ce70abd19f3512 to your computer and use it in GitHub Desktop.
alert the buttons text //source https://jsbin.com/fawepetaha
<div class="btns">
<p>Write JavaScript (using jQuery is fine) so that clicking on any button will cause an alert to popup with the text of the button that was clicked.</p>
<p>Make sure your solution is as efficient as possible even if there are a lot more <code>button.btn</code>'s added on the page. Do not use unnecessary event listeners.</p>
<button class="btn">c</button>
<button class="btn">l</button>
<button class="btn">o</button>
<button class="btn">s</button>
<button class="btn">e</button>
<button class="btn">.</button>
<button class="btn">i</button>
<button class="btn">o</button>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script id="jsbin-javascript">
var buttons = document.getElementsByClassName('btn');
function alertText(){
alert(this.innerHTML);
}
for(var i=0; i<buttons.length;i++){
buttons[i].addEventListener("click", alertText);
}
</script>
<script id="jsbin-source-javascript" type="text/javascript">var buttons = document.getElementsByClassName('btn');
function alertText(){
alert(this.innerHTML);
}
for(var i=0; i<buttons.length;i++){
buttons[i].addEventListener("click", alertText);
}</script>
var buttons = document.getElementsByClassName('btn');
function alertText(){
alert(this.innerHTML);
}
for(var i=0; i<buttons.length;i++){
buttons[i].addEventListener("click", alertText);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment