Enable disable buttons html5/css/javascript - javascript

i have made a calculator. i have uploaded it on the following webpage.
www.vipulshree.com
i want to highlight a button on clicking it and remove highlight from it when another button is clicked. when the next button is clicked, it should change color/disable/highlight and the previous button comes back to normal. Please help me ive searched all over the net for this and could not find anything. Help me im desperate.
Thank You.

You can define a class for your buttons and then using the click event you can change its color, and when you click on any button save it in variable say "previous".
So when you click any other button you again change the color of the saved button variable
and assign the current button to that variable.
var previous;
document.getElementsByClassName("className").onclick = function (){
// change the color of the previous element
previous = this;
// change the color of this button
}

Use the :focus CSS pseudo-selector. It will match the element currently having focus. Seems to not work on buttons
Use JavaScript to add a class .focused on click, and remove it on all other elements. Use event delegation on the common parent of all buttons (in this code, it's assumed to be #container).
<script type="text/javascript">
setFocus = function(e) {
if (document.getElementsByClassName('focus')[0]) document.getElementsByClassName('focus')[0].className = '';
if (e.target.tagName.toLowerCase() == 'button') {
e.target.className = 'focus';
}
};
document
.getElementById('container')
.onclick = setFocus;
</script>
My HTML markup looked like this:
<div id="container">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
</div>
Working Example

here is a little jsfiddle working example, it's using jQuery only for the dom ready loader and a CSS class to do the highlight effect.
http://jsfiddle.net/t6bJ3/
var buttons = document.getElementsByTagName('button'),
buttonsLength = buttons.length,
selected,
i = 0,
reset = function() {
for (i = 0; i < buttonsLength; i++) buttons[i].className = '';
},
highlight = function(ev) {
reset();
ev.target.className = 'highlight';
};
for (; i < buttonsLength; i++) buttons[i].onclick = highlight;

Related

Some of Icon click listeners work and some not in a strange way in JavaScript

I am working on a to-do list application. I create a li item and put 2 icons and a p tag in it. One of the icons is edit and it works quite well, I replace an input with the p tag and it is fine but the problem is that my check icons on the left side work half way. If I add the li items one by one, the check icons work very well but when I add 5 or 10 items and then try to check the icons, a few of them works and the others do not. I have tried replacing i tags with span tags and no result. It is like every second li tag blocks the former one. I need help, I would appreciate any.
I'll add below the only the icons which don't work.
const DONE = document.getElementsByClassName('far fa-circle');
const LINE = document.getElementsByClassName('list-points');
const EDIT = document.getElementsByClassName('far fa-edit');
const CONTAINER = document.getElementById("actual-container");
const BUTTON = document.getElementById("list-adder");
BUTTON.addEventListener('click', nameList);
function nameList() {
const item1 = document.createElement("i");
item1.className = "far fa-circle";
const paraph1 = document.createElement("p");
paraph1.className = "list-points";
paraph1.innerText = "Fresh again!";
const item2 = document.createElement("i");
item2.className = "far fa-edit";
const myList = document.createElement("li");
myList.appendChild(item1);
myList.appendChild(paraph1);
myList.appendChild(item2);
CONTAINER.appendChild(myList);
for (let i = 0; i < DONE.length; i++) {
DONE[i].addEventListener('click', function() {
DONE[i].classList.toggle('fa-times-circle');
})
}
}
<head>
<title>Debug</title>
<script src="https://kit.fontawesome.com/ae444f90db.js" crossorigin="anonymous"></script>
</head>
<body>
<div>
<ul id="actual-container"></ul>
</div>
<button id="list-adder">ME</button>
</body>
The error is within the assignment of your click-handlers.
You do
for (let i = 0; i < DONE.length; i++) {
DONE[i].addEventListener('click', function() {
DONE[i].classList.toggle('fa-times-circle');
});
}
This will add a toggling event handler to all elements that you keep in DONE and has this behaviour.
Click button: create elements A, assign click handler to A
(A has a single handler) works
Click button: create elements B, assign click handler to A and B
(A has two handlers) does not work
(B has a single handler) works
Click button: create elements C, assign click handler to A and B and C
(A has three handlers) works
(B has two handlers) does not work
(C has a single handler) works
Because you are using toggle in your click handler, the handlers are "canceling" each other because toggling something twice will leave you in the initial state.
I guess you are not aware of the fact that getElementByClassName returns a live list, so that the elements of your variable DONE are changed when you add new elements to the DOM. I was not aware of this either, so thank you for your question :)
See here for a better explanation: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
In your code it should be enough to add the handler just to the one element you create (item1 is the icon element in your code):
item1.addEventListener('click', function() {
item1.classList.toggle('fa-times-circle');
});

How to clear input with :after element

Take a look at this website. There are 2 search bars and after each search bar there is an :after element. When you click that element the text box is cleared. How can I do this with Javascript ? (no jquery)
You can't add event listeners to pseudo-elements. But here the element has no contents except the pseudo-element, so you can just add the event listener to the element.
var input = document.getElementById('input');
document.getElementById('clear').addEventListener('click', function() {
input.value = '';
});
#clear::after {
content: '\00d7';
cursor: pointer;
}
<input id="input" value="Hello" />
<span id="clear" title="Clear"></span>
The click event is actually not on the :after pseudo-element, but on the span itself (as you can see here) The pseudo-element just provides the icon, nothing fancy going on here. Then it's just a matter of doing something like this;
element.addEventListener('click', function() {
document.getElementById('startInput').value = '';
}, false);
I don't think it's anything special.
Something like this:
var elementList = document.getElementsByClassName('something');
for (var i = 0; i < elementList.length; i++) {
elementList[i].addEventListener("click", delFn);
}
function delFn(){
console.log("delete it");
}
https://jsfiddle.net/5w4obgzu/1/

DOM: Delete newly created 'article' element with newly created delete button within onclick event?

I have one section element that contains one article element. Also, I have one input button with 'onclick' event. Whenever this event fired, a new article element appended to the section element with unique id.
The newArticle element contains a label, text box and a delete button. All these three elements get created within the on-click event.
document.getElementById("addRow").onclick = function () {
var newCustomerlbl = document.createElement("label");
newCustomerlbl.innerHTML = "Cutomer Name: ";
var newCustomertxt = document.createElement("input");
newCustomertxt.setAttribute("type", "text");
var delBtn = document.createElement("input");
delBtn.setAttribute("type", "button");
delBtn.setAttribute("value", "Delete");
delBtn.setAttribute("id", "btnDelete");
var newArticle = document.createElement("article");
newArticle.appendChild(newCustomerlbl);
newArticle.appendChild(newCustomertxt);
newArticle.appendChild(delBtn);
var customerSection = document.getElementById("customerRecords");
var customerArticles = customerSection.getElementsByTagName("article");
for (var i = 0; i < customerArticles.length; i++) {
var lastDigit = i + 1;
var newArticleValue = "article" + lastDigit;
newArticle.setAttribute("id", newArticleValue);
}
customerSection.appendChild(newArticle);
}
Now what I want is whenever user click upon the newly created appended delete button, only that particular article get deleted without effecting the rest of articles.
Here is the my jsFiddle code.
If you don't want to use jQuery you can add event listeners to your buttons:
delBtn.addEventListener('click', function () {
this.parentElement.remove();
}, false);
https://jsfiddle.net/3nq1v5e1/
You need to bind an event listener on the newly created delete button. Your example code about using $(this) suggest that you are using JQuery, but then again in the rest of the code you are not using any JQuery?
If you are using JQuery, things get real simple, just add something like
$(document).on('click','.btnDelete', function(){
$(this).closest('article').remove();
});
(and remember to give the deletebutton a CLASS rather than ID, as there will be multiple delete buttons).
If you are NOT using JQuery, you need to add the event listener EVERY TIME a new delete button is created
newArticle.appendChild(delBtn);
delBtn.onclick = function(.....
etc.

getElement 1 and do1, getElement 2 and do2, getElement 3 and do3

I have this code for smooth scrolling, it works great but only for one "clickme" id, how could i use this code for multiple tabs whit i++
<div class="navbar">
<button type="button" id="clickme1">Scroll to red section!</button>
<button type="button" id="clickme2">Scroll to blue section!</button>
</div>
<div class="second" id="second">Hello</div>
<div class="tab1" id="tab1">The start of the red section!</div>
<div class="tab2" id="tab2">The start of the blue section!</div>
and here is the pure javascript that i want to use, please do not recommend me jQuery and anchor navigation.
document.getElementById('clickme1').addEventListener('click', function() {
var header = document.querySelectorAll('.navbar');
aim = -header[0].clientHeight;
initial = Date.now();
smoothScroll(document.getElementById('tab1'));
});
*******or more simplified, how can i make this code shorter:*******
document.getElementById('clickme1').addEventListener('click', function() {
var header = document.querySelectorAll('.navbar');
aim = -header[0].clientHeight;
initial = Date.now();
smoothScroll(document.getElementById('tab1'));
});
document.getElementById('clickme2').addEventListener('click', function() {
var header = document.querySelectorAll('.navbar');
aim = -header[0].clientHeight;
initial = Date.now();
smoothScroll(document.getElementById('tab2'));
});
here is JSFIDDLE
You can do something like following
// Get buttons
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
// Iterate over buttons and add handler
buttons[i].addEventListener('click', clickHandler, false);
}
// Handler function
function clickHandler(){
var counter = this.id.substring(7); // Substring id to get counter
var header = document.querySelectorAll('.navbar');
aim = -header[0].clientHeight;
initial = Date.now();
smoothScroll(document.getElementById('tab'+counter));
}
Note : As you can have some other buttons on your page and do not want to add this handler to them, so, in place of tag name selector, I will suggest you to add a specific class to the button elements and then use class selector to get elements.
You should consider using proper anchor links with progressive enhancement for smooth scrolling. This would involve either changing the buttons to <a> tags or just wrapping them:
<div class="navbar">
<button type="button">Scroll to red section!</button>
<button type="button">Scroll to blue section!</button>
</div>
You can then use event delegation to trap clicks on any anchor link at the document level:
document.addEventListener('click', function (evt) {
var tgt = evt.target;
if (tgt.tagName === 'A' && tgt.getAttribute('href')[0] === '#') {
smoothScroll(document.getElementById(tgt.hash.slice(1)));
}
});
There are numerous benefits to this approach, including:
Ability to hotlink to a section by copy/pasting the URL
Graceful degrading when JavaScript is not present.

Click All Buttons on Page

I was wondering if anyone could help with a simple JavaScript code to click all buttons with the same value name/input name on a page?
They each share:
<input name="all" type="submit" value="Do All">
Here's a screenshot of the buttons: http://oi61.tinypic.com/2nqblnr.jpg
Maybe one should make a button that works as a "click all" button? This will be a chrome extension (for personal use), so I can't really go about changing the "do all" button's code.
I was having a hard time finding it on Google, and I'm fine with HTML/CSS but really terrible with JavaScript.
To click all the buttons on the page with the same name you can use getElementsByName() function and set it to a variable which will hold all the buttons in a NodeList then loop through the NodeList and call the click() event for each button.
For example:
// Get all buttons with the name 'all' and store in a NodeList called 'buttons'
var buttons = document.getElementsByName('all');
// Loop through NodeList and call the click() function on each button
for(var i = 0; i <= buttons.length; i++)
buttons[i].click();
// Select all buttons with class .btn
const inputBtns = document.querySelectorAll('[name="all"]');
// Select click all button
const clickAllBtn = document.querySelector('.click-all');
// Attach click handler to all input buttons
for(let i = 0; i < inputBtns.length; i++) {
inputBtns[i].addEventListener('click', function() {
alert(this.value);
})
}
// Click all buttons, when user click .click-all button
clickAllBtn.addEventListener('click', function() {
for(let i = 0; i < inputBtns.length; i++) {
inputBtns[i].click();
}
})
<input name="all" type="submit" value="Do All 1">
<input name="all" type="submit" value="Do All 2">
<button type="button" class="click-all">
click all
</button>
This worked for me assuming the of those elements had href="#show" or something similar
var buttons = document.querySelectorAll('[href="#show"]');
for(var i = 0; i <= buttons.length; i++)
buttons[i].click();
I guess this is what you want to achieve :
jsfiddle : http://jsfiddle.net/vqk2V/
Achieved using .click()[http://api.jquery.com/click/] method of jquery.
With Java...maybe using Selenium. But you can use jquery (javascrpt's framework) so the code could be:
<scrpipt>
function ClickAllButtons()
{
if($("input[type=button][name='someName']").length > 0)
{
$('input[type=button]').each(function(i){
var $currentButton = $(this);
$currentButton.click();
});
}
}
</script>
var buttons = document.getElementsByClassName('uArJ5e');
// Loop through NodeList and call the click() function on each button
for(var i = 0; i <= buttons.length; i++)
buttons[i].click();
This will click all buttons on google ;)
What you would want to do is create a class eg.
public class MyClass{
........
}
..and then create methods which do the processing that is done when you click your buttons.
Then call the methods with an object if your methods are non static in the specific buttons you require the method in.
Now you can create a button which calls all the methods you want to call and it will do what you are asking for.

Categories

Resources