Is there a way to deselect or unclick a button that has been clicked using javascript?
So basically I have a button:
if (i === 10) {
var clicked = document.getElementById('i10');
clickedButton.push(click.textContent);
clicked.style.color = "pink";
}
So when i click that button it turns the text to pink. Is there a way to click on the button again and have it remove the push and turn the text back to black?
Sorry, Javascript isn't my strongest point.
Web programming lesson time: if you want to set styles, don't use JavaScript to set the style, use CSS for the styling definitions, and then only use JavaScript to point to that CSS.
In your CSS:
.highlight {
color: pink;
background: blue;
font-style: fantasy;
whatever-else: StuffGoesHere;
}
And then your button handling:
button.addEventListener("click", function(evt) {
var e = find.your.element.however.you.need();
e.classList.toggle("highlight");
});
Magic: simply by doing things the right way, the code is extremely straight forward, AND we're not hardcoding the styling, we're simply referring to where styling should be defined.
"But what if the browser doesn't support .classList?": the only reason to say this is because you did not keep up with how much browser have improved. Every browser supports classList.
Of course, if you need to do more than just toggles, write your function as a standalone operation, and throw elements at it:
var records = {};
function toggleHighlight(e) {
e.classList.toggle("highlight");
if (e.classList.contains("highlight")) {
// element is now highlighted, do things accordingly:
records[e.id] = e.textContent;
// ...
} else {
records[e.id] = false;
// ...
}
}
button.addEventListener("click", function(evt) {
var e = find.your.element.however.you.need();
toggleHighlight(e);
});
Do this help you?
function onclick(){
var clicked = document.getElementById('i10');
if(clicked.style.color == "pink"){
clicked.style.color == "black";
}
else{
clicked.style.color == "pink";
//do your businesses
}
}
From the shared code, you can do something like check if the textContent already exists in teh array if so it is already clicked so remove it from the array and change the color
if (i === 10) {
var clicked = document.getElementById('i10'),
index = clickedButton.indexOf(click.textContent);
if (index > -1) {
clickedButton.push(click.textContent);
clicked.style.color = "pink";
} else {
clickedButton.splice(index, 1);
clicked.style.color = "";
}
}
Yes:
if (i === 10) {
var clicked = document.getElementById('i10');
var index = clickedButton.indexOf(click.textContent);
if (index === -1) {
// toggle on
clickedButton.push(click.textContent);
clicked.style.color = "pink";
} else {
// toggle off
clickedButton.splice(index, 1);
clicked.style.color = "";
}
}
This will check if click.textContent is already in the clickedButton array. If it is it will remove it from that array as well as reset button color to whatever default is.
Please note that, searching arrays using indexOf is not supported in IE7-8. If you need support for those browsers, you will need to implement this as well:
if (!('indexOf' in Array.prototype)) {
Array.prototype.indexOf= function(find, i /*opt*/) {
if (i===undefined) i= 0;
if (i<0) i+= this.length;
if (i<0) i= 0;
for (var n= this.length; i<n; i++)
if (i in this && this[i]===find)
return i;
return -1;
};
}
The above is taken from StackOverflow thread: Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.).
Related
I want to change the color of specific table cells when clicking a button.
<button onclick="highlight()">Toggle highlighting</button>
And JS:
function highlight() {
var x = document.getElementsByClassName('best');
for (var i = 0; i < x.length; i++) {
x.get(i).style.color = "green";
}
}
I added the table cells I want to change to the class "best", but when clicking the button, nothing changes. I first tried to assign them all to a single ID and use document.getElementById('best').style.color = "green";, but this only changed the first element that had the id "best" and not all. How should highlight() look like?
You don't need to use x.get(i) there. Just access the element using x[i]
See the following code:
function highlight() {
var x = document.getElementsByClassName('best');
for (var i = 0; i < x.length; i++) {
x[i].style.color = "green";
}
}
First off, I'd recommend using Javascript's built in forEach() function when working with a nodeList like this as there is less chance of an off by one error:
bestElements.forEach(best => {
best.style.color = "green";
});
Second, I believe you may be looking for the background-color attribute, not the color attribute if you are trying to change the color of the entire cell.
bestElements.forEach(best => {
best.style.backgroundColor = "green";
});
I'm very new to learning JavaScript, and I've tried to read, and look for similar answers, but everything is pointing at jQuery, which I want to avoid using for this problem. I can't quite work out what is jQuery and what still works in JS...
I have set up a function that can grab the innerHTML but I can't seem to assign it to the same classes, else it'll only work on the first instance, and I tried creating multiple classes but essentially they're all the same button with different values...
document.querySelector(".b1").addEventListener("click", writeDisp);
document.querySelector(".b2").addEventListener("click", writeDisp);
document.querySelector(".b3").addEventListener("click", writeDisp);
document.querySelector(".b4").addEventListener("click", writeDisp);
function writeDisp() {
if(dispNum.length < 9){
if(dispNum === "0") {
dispNum = this.innerHTML
} else {
dispNum = dispNum + this.innerHTML};
document.querySelector(".display").textContent = dispNum;
}
}
}
How can I make this more simple. As there are way more .b* classes to add, and I'd rather not have a massive list if possible.
Thanks,
var class_elem = document.querySelectorAll("button[class^='b']");
function writeDisp(){
if(dispNum.length < 9){
if(dispNum === "0"){dispNum = this.innerHTML}else{dispNum = dispNum + this.innerHTML};
document.querySelector(".display").textContent = dispNum;
}
}
for (var i = 0; i < class_elem.length; i++) {
class_elem[i].addEventListener('click', writeDisp, false);
}
//Here your code in javascript only.
If you don't want to use jquery, you can use native document.querySelectorAll API like this
function writeDisp(){
if(dispNum.length < 9){
if(dispNum === "0"){
dispNum = this.innerHTML
} else {
dispNum = dispNum + this.innerHTML
}
document.querySelector(".display").textContent = dispNum;
}
}
// this line will select all html tags that contains a class
// name starting with 'b'
var doms = document.querySelectorAll("[class^=b]");
doms.forEach(function(dom) {
dom.addEventListener('click', writeDisp);
})
Note
querySelectorAll will fetch only those DOM instance in which b* is defined as first class, so in case of multiple class defintion, it will not fetch those DOMs which don't have the desired classname at first. That means if you have a DOM defintion like <div class="a box"></div>, this will be ignored, as here, classname starting with b sits after a class.
I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")
i have this code
Click Me
Click Me 2
And then the Js
var mainLinker = document.getElementsByTagName('a');
for (var i = 0; i < mainLinker.length; i++) {
this.style.color = 'red';
}
But i get this error
Cannot set property 'color' of undefined
Please tell me where am i doing it wrong.
this is not what you want.
Change the loop body to
mainLinker[i].style.color = 'red';
or equivalently use forEach (edited with #Vohuman's comment):
[].forEach.call(document.getElementsByTagName('a'), function(el) {
el.style.color = 'red';
});
You refer to this in an object
Your function is not in an object
This will work
var mainLinker = document.getElementsByTagName('a');
for (var i = 0; i < mainLinker.length; i++) {
mainLinker[i].style.color = 'red';
}
Of course your basic problem is using this, as pointed out in other answers. But why are you doing this instead of using a CSS rule such as
a { color: red; }
If you want to make this conditional somehow, then add a class at a higher level, such as body, to control it:
body.make-links-red a { color: red }
Then, when you want to make links red, do
document.body.classList.add('make-links-red')
I have a Boolean variable. It is stored in a hidden input field. Basically, if the user is signed in, it is false, if not, it is true.
There are download buttons which will link to a file download. My aim is to make it so that, if they aren't signed in, the button will not show, and the link will not work (it would be nice to have an alert saying they need to sign in or something, but that would probably be more effort than it's worth).
I have a function that performs onload of body:
function hide_download_btns(){
if (document.getElementById('download_btn_var_input').value == "true") {
document.getElementsByClassName('project_download_btn').item(0).hidden = true
}
}
My problem is where it asks for the nth term .item(0). This is where it selects the div on which to perform the function, however, I want the function to affect all divs with the class name 'project_download_btn'.
I'm not a fan of jQuery, so it would be great to avoid that if possible.
You can simply loop through the elements instead of just taking the 0th.
var buttons = document.getElementsByClassName('project_download_btn');
for(var i=0; i< buttons.length; i++){
buttons[i].hidden = true;
}
if (document.getElementById('download_btn_var_input').value == "true") {
var el = document.getElementsByClassName('project_download_btn');
for (var i = 0; i < el.length; i++) {
el[i].hidden = true;
}
}
document.getElementsByClassName returns array so what you are interested is :
document.getElementsByClassName('project_download_btn')[0]
Loop through each div that contains your download button and set hidden to true:
if (document.getElementById('download_btn_var_input').value == "true") {
var button_divs_array = document.getElementsByClassName('project_download_btn');
for (var i = 0; i < button_divs_array.length; i++) {
button_divs_array[i].hidden = true;
}
}