I have a element with an id="caretToggle" and a button with onclick="caretToggle()". This fires a function that adds a class to invert the caret on the button.
I am successful in running:
function caretToggle() {
var caretElement = document.getElementById("caretToggle");
caretElement.classList.add("dropup");
}
But This leaves the caret inverted after the collapse is closed. I want to toggle the caret once the button is clicked again.
This is my condition code that I have failed to get working:
function caretToggle() {
var caretElement = document.getElementById("caretToggle");
if (caretElement.classList.contains("dropup")) {
caretElement.classList.remove("dropup");
} else {
caretElement.classList.add("dropup");
}
}
Thank you in advance for any help you may provide!
You dont need to check wheter contains or not.
What you can do simply use toggle function on classList :)
function caretToggle() {
var caretElement = document.getElementById("caretToggle");
caretElement.classList.toggle("dropup");
}
And also there is a conditional toggle like:
caretElement.classList.toggle("dropup", counter < 10)
Check here from MDN
If you want to toggle class simply do it like this
let caretElement = document.getElementById("caretToggle");
function caretToggle() {
caretElement.classList.toggle("dropup");
console.log('class attribute contains: ', caretElement.className)
}
span {
margin:10px;
}
.dropup {
background-color: purple;
padding: 1em;
border-radius: 10px;
color: white;
}
<span id="caretToggle">HTMLElement</span>
<br/>
<br/>
<br/>
<br/>
<button onclick="caretToggle()">Click</button>
Related
I have the following two scss files, and I'm trying to change an attribute that is set when I import an already built component. The first file is the css I'm changing, and the second is the css I'm pulling from. I can't change the second file without messing up the component already built, but I can't seem to figure out how to modify this one attribute...
.button-edit {
.imported-button {
width: 200px;
}
}
.imported-button {
width: 300px;
.imported-button-color {
color: red;
}
}
I have figured out how to change the width through the first code block I've shown above, but how would I change the color from red to blue, for example? I've tried...
.button-edit {
.imported-button {
width: 200px;
.imported-button-color {
color: blue;
}
}
}
... but that doesn't change anything for me. Appreciate the help!
Edit: The Javascript being used is structured like...
<BoxButton className='button-edit'>
<div>
<p>Press here</p>
</div>
</BoxButton>
where the Button component has the css attributes in the .imported-button class
First, you have an error in your code, why did you write className in the html code?
<Button className='button-edit'>
<div>
<p>Press here</p>
</div>
</Button>
you should just write class
<Button class='button-edit'>
<div>
<p>Press here</p>
</div>
</Button>
Second, you have a problem arranging the elements within the scss code, as you want the blue color to activate when its parent class is deleted! How do you want this to be done? This command cannot be implemented because you are asking the language to break its programming to implement your goal
To solve this problem, you have to remove the blue color class from inside the dev whose class you want to delete, so that it becomes as follows
.button-edit {
.imported-button {
width: 200px;
}
.imported-button-color {
color: blue;
}
}
Now we come to JavaScript:
1- We make variables that carry the father div and p
let checkDiv = document.querySelector(".button-edit div")
let checkDivP = document.querySelector(".button-edit div p")
2- We make a function on the button so that it contains two conditions
document.querySelector(".button-edit").addEventListener("click",function(){
if( checkDiv.className === "" )
{
checkDiv.className = "imported-button";
checkDivP.className = ""
}
else
{
checkDiv.className = "";
checkDivP.className = "imported-button-color"
}
})
first condition
if( checkDiv.className === "" )
{
checkDiv.className = "imported-button";
checkDivP.className = ""
}
If the class is empty, add the width class and delete the color class
second condition
else
{
checkDiv.className = "";
checkDivP.className = "imported-button-color"
}
If the width class exists, delete it and add the color class
The final result / https://codepen.io/emozlove/pen/JjpjmQR
Salutations,
I am learning to code through some online resources and my brother who works in the field in an effort to get into a development career. Right now I am working on a silly web app where you are matching photos. Below each photo is a button with a unique ID. Currently, when you select a button, it will turn blue.
I am trying to create a function that will look for 2 specific buttons being clicked.
If I were to speak what I want it to do in a conversation with you, I would say "if button1 is select when button4 is selected, do this thing"
What function am I looking for?
Can anyone help this n00b out?
Below I have the function as is for when a button is clicked. The class changes in order to adjust the color.
I can post whatever code is necessary, otherwise this is all I could think to post. {BC1b is a button that should be paired with F1b}
function sbtnb1() {
document.getElementById("BC1b").className = "selected";
}
Here is an example.
https://jsfiddle.net/273rhzyw/
With Jquery
https://jsfiddle.net/agoLcuv8/8/
// All buttons with class of button
const buttons = document.querySelectorAll(".button");
// declare array to keep the match checks
let matchCheckerArray = [];
// Loop through each button and attach an onClick
buttons.forEach(function(button) {
button.onclick = function() {
clickHandler(button);
}
});
const clickHandler = function(button) {
matchCheckerArray.push(button.dataset.matchId)
console.log(matchCheckerArray);
if (matchCheckerArray.length == 2) {
if (isMatch()) {
alert('Match');
}
matchCheckerArray = [];
return;
}
}
const isMatch = function() {
if (matchCheckerArray[0] === matchCheckerArray[1]) {
return true;
}
return false;
}
I would keep two global variables (or an array/set of variables) that store what's been clicked. You can manipulate these however you'd like (e.g. clear out the selection if the user selected two photos that aren't a match; don't let the user select a second card if it doesn't match; etc...).
This can work in conjunction with what you already have. The class name will allow you to add specific selected styling, while the global variables allow you to keep track of what has been selected. The global variables will also allow you to check for match or no match.
There are many ways to do this but this is how I would go about it.
$(".checkButton").on("click", function(){
// toggle button state
if($(this).attr("data-state") == "on") {
$(this).attr("data-state", "off"); // toggle button off
$(this).removeClass("highlight"); // remove highlight
$(".myImage").removeClass("highlight"); // remove highlight
} else {
$(this).attr("data-state", "on"); // make button active
$(this).addClass("highlight"); // add highlight
}
//----------------------------------------------------------
// Here you would have to build your checks and how you want
// the comparison of buttons and images to be linked.
//----------------------------------------------------------
// For example:
// check if more than 2 buttons are active and if buttons match the if statement.
var buttonCount = 0;
$("#buttonContainer button").each(function(){
if($(this).attr("data-state") == "on"){
buttonCount += 1;
}
});
// if 2 buttons are clicked then check then allow to do something
if(buttonCount == 2){
// highlight image 1 if buttons 1 and 2 are on.
if($(".checkButton[data-id=b1]").attr("data-state") == "on" &&
$(".checkButton[data-id=b2]").attr("data-state") == "on"){
$("#image1").addClass("highlight");
}
// highlight image 2 if buttons 3 and 4 are on.
if($(".checkButton[data-id=b3]").attr("data-state") == "on" &&
$(".checkButton[data-id=b4]").attr("data-state") == "on"){
$("#image2").addClass("highlight");
}
}
//----------------------------------------------------------
});
.myImage {
width: 100px;
height: 100px;
margin: 5px;
background: black;
float: left;
}
.highlight {
outline: 2px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width: 100%; height: 110px;">
<div class="myImage" id="image1"></div>
<div class="myImage" id="image2"></div>
</div>
<div id="buttonContainer" style="width: 100%;">
<button class='checkButton' data-id="b1" data-state='off'>button 1</button>
<button class='checkButton' data-id="b2" data-state='off'>button 2</button>
<button class='checkButton' data-id="b3" data-state='off'>button 3</button>
<button class='checkButton' data-id="b4" data-state='off'>button 4</button>
</div>
I have a set of buttons on my page, each of which calls a javascript function when clicked; when clicked, the active link color is lit, but when I click elsewhere on the page the active link color is cleared. I want it to stay lit unless I click on another button link.
Here is an example of how a link is constructed (there are 10 links):
<div class="C1"><br><button class="button_01" onclick="HideDropdown(); ShowPage(7);">FAQs</button></div>
Here's the css for the button and C1 classes:
.button_01 {
background-color: rgb(0,2,3);
border: none;
color: rgb(100,100,100);
font-family: camphorW01-Thin,calibri,arial;
text-align: left;
text-decoration: none;
font-size: 13pt;
cursor: pointer;
transition: all 150ms ease-in;
}
.button_01:hover { color: rgb(175,222,162); }
.button_01:active { color: rgb(175,222,162); }
.button_01:focus { color: rgb(175,222,162); }
.button_01:visited { color: rgb(175,222,162); }
.C1{
color:#DBDBDB;
font-family: sans-serif;
font-size: 14pt;
text-indent: 0px;
width: auto;
margin: auto;
}
I know the default behavior is for the active link color to clear when clicking elsewhere, but I should be able to use javascript or jquery to get the value of the active link and keep it the same color (unless I click on another link); I've found only two posts that come close but one is specific to list items (li), not a button class with an onclick handler (not an anchor tag) at How to get the ID of an active link. Another post at how to Keep the color of active link constant, until i press other link showed a jquery function specific to anchor tags; I modified it like this:
<script>
var items = $("button_01");
items.removeClass("active");
$(this).toggleClass("active");
});
<script>
That doesn't work and with that script in place the links do not work.
So my question is: how do I keep the active link color lit on a button that has an onclick handler to call javascript (versus a list item or an anchor tag)?
Thanks very much for any help on this.
EDIT: I solved this problem and posted the answer below.
assuming all you buttons have class="button_01"
$('.button_01').on('click', function(){
$('.button_01').removeClass('active');
$(this).addClass('active');
});
.active {
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button_01">Button 1</button>
<button class="button_01">Button 2</button>
<button class="button_01">Button 3</button>
you could use the .css() property within jquery if the active attribute is still clicking out on your site.
$('.button_class').on('click', function() {
$('.button_class').removeAttr('style');
$(this).css('backgroundColor', 'red');
});
I just made a quick fiddle with what I think is a possible solution to your problem. I've done in pureJs.
function ShowPage(e,page){
// do a function to reset colors to default
resetColors();
// call hide here, since you do it everytime you show a page
HideDropdown();
e.classList.add("active");
//do stuff here
}
function HideDropdown(){
// do stuff here
}
function resetColors(){
// do stuff here
}
.active{
color: red !important;
}
<div class="C1">
<button class="wathever" onclick="ShowPage(this,7);">A</button>
<button class="wathever" onclick="ShowPage(this,7);">B</button>
<button class="wathever" onclick="ShowPage(this,7);">C</button>
<button class="wathever" onclick="ShowPage(this,7);">D</button>
</div>
After much research and work, here's how I solved this problem.
Remember that I have 10 links, each with a unique ID number, so I loop through them 1-10 and create the ID name (e.g., btn04). In order to keep the current active link lit, I have to change the link color to the active link color when I click anywhere on the page except for another link of the same type (button_01 class). For that, I need to store the active element in a global var on each button click, so that on any subsequent click we know what the last active element was BUT the subsequent click will change the active element to the currently-clicked element. What to do? I set up another global var, LastActiveElement, which captures the most recently set active element. Now I know where the last click was -- if it was a hyperlink and the current click is not a hyperlink, I change the last clicked hyperlink color back to its active color, which has the effect of keeping it on the same color.
Add this to the body tag:
<body onload="ShowABC(1);" onclick="changeColor(event); getLastGAE(event); getFocusElement(event);">
<script>
function changeColor(event) {
for (i = 1; i < 11; i++) {
ID_Name = "btn0" + i.toString();
if (i >= 10){ID_Name = "btn" + i.toString();}
var elem = document.getElementById(ID_Name);
TargetClass = event.target.getAttribute('class');
TargetID = event.target.getAttribute('id');
var active = document.activeElement;
var equal = (LastActiveElement == ID_Name);
tfh = TargetID == "hamburger_container";
if ((equal == "true") && (TargetClass != "button_01") && (tfh == "false")){
var newColor = "rgb(175,222,162)";
elem.style.color = newColor; }
if (TargetClass == "button_01"){ elem.style.color = "rgb(100,100,100)"; }
if (TargetID == ID_Name){ elem.style.color = "rgb(175,222,162)"; }
}
}
</script>
<script>
var LastActiveElement;
function getLastGAE(event) {
LastActiveElement = GlobalActiveElement;
}
</script>
<script>
var GlobalActiveElement;
function getFocusElement(event) {
var active = document.activeElement;
TargetID = event.target.getAttribute('id');
GlobalActiveElement = TargetID;
}
</script>
With that, if I click anywhere on the page except another hyperlink of the same class, the active link color does not change.
Now I know some advise against global vars, but this is only two data elements added to the DOM so it takes up negligible space.
Of course, there may be other solutions but this is what I came up with.
Thanks to everyone who replied to this question.
If I've got multiple items that I want to change from a display of 'none', to a display of 'block', what's the most efficient way of doing it?
The JS I would use for a single item is below, but I imagine there are several on a page or site. Should I make use of function constructors somehow?
var sideNav = document.getElementById('sideNav');
var menuButton = document.getElementById('menuButton');
function toggle() {
if(sideNav.style.display) {
sideNav.style.display = '';
} else {
sideNav.style.display = 'block';
}
}
menuButton.addEventListener('click', toggle);
Take a look, see if this helps you.
I did it with vanilla JS, I don't know if you are currently using jQuery (would be easier if yes)
What I did:
Every button have it's own id that is used to "connect" to the elements that it should toggle.
First I add the listener to all buttons, passing it's id when the function is called.
Then in the function, I used document.querySelectorAll to get all elements with the class that should be hidden/show.
Then finally I run a loop in those elements, showing or not showing, depending on it's current 'display'.
var menuButtons = document.querySelectorAll('.menuButton');
menuButtons.forEach(function(btn){
btn.addEventListener("click", toggle.bind(this, btn.id));
})
function toggle(id) {
var sideNav = document.querySelectorAll('.nav_' + id);
sideNav.forEach(function(el){
if (el.style.display == 'none'){
el.style.display = "block";
} else {
el.style.display = "none"
}
})
}
div{
height: 30px;
width: 50px;
margin: 2px 0;
background: #999;
text-align: center
}
<button id="menuButton1" class="menuButton">Toggle 1</button>
<button id="menuButton2" class="menuButton">Toggle 2</button>
<button id="menuButton3" class="menuButton">Toggle 3</button>
<div class="nav_menuButton1">1</div>
<div class="nav_menuButton1">1</div>
<div class="nav_menuButton2">2</div>
<div class="nav_menuButton3">3</div>
<div class="nav_menuButton3">3</div>
<div class="nav_menuButton3">3</div>
Probably there are better approaches, but I'm now in a hurry and this is the best I could think in that moment
Use JQuery to obtain it:
$(document).ready(function(){
$('#menuButton').click(toggle);
});
function toggle(){
$('.toggle-item').each(function(){
$(this).show();
})
}
and for all you items, add the toggle-item class with this css:
.toggle-item{
display: none;
}
If for every button there is an item to show, this is the way:
$(document).ready(function(){
$('.menuButton').each(function(){
var button = $(this);
button.click(function(){
toggle(button.attr('data-target')));
});
});
});
function toggle(itemId){
$(itemId).show();
}
Adding this attribute to button:
<button class="menuButton" data-target="#toggle-item-1"></button>
I an creating a project where people can create posts. I have a text editor I'm creating for this section. I need to make text uppercase if user clicks a button. All these other buttons work with execommand but there isnt an option for uppercase. My question is there an alternative I can use to do this?
Javascript
function headBold() {
document.execCommand('styleWithCSS', false, true);
document.execCommand('bold',false,null);}
function headItalics() {
document.execCommand('styleWithCSS', false, true);
document.execCommand('italic',false,null);}
function headUndLne() {
document.execCommand('styleWithCSS', false, true);
document.execCommand('underline',false,null);}
function headuppercase() { }
HTML
<button type="button" onclick="headBold();" class="bolden">B</button>
<button type="button" onclick="headItalics();" class="italics"><i>I</i></button>
<button type="button" onclick="headUndLne();" class="underline">U</button>
<button type="button" onclick="headuppercase();" class="upperCase">Tt</button>
This is being used in a content editable div not an input.
Please no JQuery.
The effect I'm looking for is the same one in CSS.
font-variant: small-caps;
There's no command identifier for font-variant:small-caps. The demo is solution that'll compliment an editor such as yours, but it doesn't use execCommand but it performs exactly like one.
function tags(tag, klass)
Usage: Select some text, then call tags("span", "sC")
Creates a tag with the specified class from the required parameters.
Uses the Range and Selection API to wrap the dynamically created tag around the selected text.
Result: <span class="sC">Sᴏᴍᴇ Tᴇ𝘅ᴛ</span>
function setB() {
document.execCommand('bold', false, null);
}
function setI() {
document.execCommand('italic', false, null);
}
function setU() {
document.execCommand('underline', false, null);
}
function setsC(e) {
tags('span', 'sC');
}
function tags(tag, klass) {
var ele = document.createElement(tag);
ele.classList.add(klass);
wrap(ele);
}
function wrap(tags) {
var select = window.getSelection();
if (select.rangeCount) {
var range = select.getRangeAt(0).cloneRange();
range.surroundContents(tags);
select.removeAllRanges();
select.addRange(range);
}
}
#editor {
min-height: 100px;
width: 80%;
border:4px inset grey;
padding:3px 5px;
}
.sC {
font-variant: small-caps
}
<section id='editor' contenteditable='true'></section>
<button type="button" onclick="setB();" class="bd"><b>B</b></button>
<button type="button" onclick="setI();" class="it"><i>I</i></button>
<button type="button" onclick="setU();" class="uL"><u>U</u></button>
<button type="button" onclick="setsC();" class="sC">Tt</button>
Create a function where you get the input you are trying to transform the text to uppercase to:
var headUpperCase = function(){
var inputValue = document.getElementById("your-input").value;
inputValue = inputValue.toUpperCase();
}
and then
<button type="button" onclick="headuppercase();" class="upperCase">Tt</button>
I would use text-transform:uppercase;, it will make the inner text of the div capitalized.
function makeUpperCase() {
var contentDiv = window.document.getElementById("editable-container");
var contentDivTextTransform = contentDiv.style.textTransform;
if(contentDivTextTransform === "uppercase") {
contentDiv.style.textTransform = "";
} else {
contentDiv.style.textTransform = "uppercase";
}
}
Here is a fiddle