Cannot get button click to toggle class - javascript

No matter what I try to do, I cannot get classes to toggle on a button click. I have tried many different ways and no matter what I do I cannot get it to work. I think I am making a very simple mistake but I haven't been able to figure it out. I am trying to figure this out so that I can build a navigation that goes in and out of view after you click a button.
document.querySelector("btn-toggle").addEventListener("click",
function() {
document.getElementById("myDIV").classList.toggle("style");
});
.style {
background: green;
font-size: 40px;
}
<button class="btn-toggle">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>

.btn-toggle is the class name of the button, so you need to select the class appropriately - with querySelector, that would be ".btn-toggle". (The . in front indicates to search for a class with that name)
document.querySelector(".btn-toggle").addEventListener("click",
function() {
document.getElementById("myDIV").classList.toggle("style");
});
.style {
background: green;
font-size: 40px;
}
<button class="btn-toggle">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
Using querySelector("btn-toggle") indicates that you're searching for an element whose tag name is btn-toggle, which is not what you want.

You should add a dot to your selector to make it a class selector.
For example ".btn-toggle" would match your button. With code you have shown us querySelector will search for a tag named btn-toggle.

Related

I can't change the color to red in javascript

I'm trying to change the color of a p tag using JavaScipt (onclick), in w3schools it shows:
function myFunction() {
document.getElementById("demo").style.color = "red";
}
but I don't like the document.getElementById thing so I'm wondering how to replace it.
I am trying with
function change() {
document.write(color().style.color = red);
}
but it's not working. (Keep in mind I am new to javascript) Thanks. :)
You can use document.querySelector which is quite similar to document.getElementById and in your case, it does the same. Note that document.write is not the right method this time, because it writes text directly to an HTML document and you cannot use it for changing the colour of an element.
document.querySelector(element) gets the first element with the given id or
class in the parentheses
function myFunction() { document.querySelector("#demo").style.color = "red"; }
#demo{
width: 200px;
height: 100px;
background-color: blue;
}
<div id="demo">Watch me change</div>
<button onclick="myFunction()">Change color</button>
Reference
W3Schools: document.querySelector
Read about what document.write() does
You can use the this keyword.
this.style.color = 'red';
To change the style of an element, you need a reference to that element which is exactly what document.getElementById gives you. There are other methods too but since you are using it as onclick listener, you can make use of the fact that this keyword contains the reference to the targeted element.
Sample Snippet:
<p onclick="this.style.color='red'">Click this to change color to red</p>
document.write accepts a value to output to the document
function change() {
document.write(<div id='demo' style='color: red'>TEXT</div>);
}
Well, if you don't like JavaScript(document.getElementById) {But Why?}, you could go with some CSS like this:
The :active selector is used to select and style the active link. A
link becomes active when you click on it. The :active selector can be
used on all elements, not only links.
p {color: blue;cursor: pointer;}
p:active {color: red}
<p> I change color when clicked </p>

How to make HTML text hidden until clicked on

I'm trying to learn how to make HTML text toggle with jQuery, which is pretty easy in itself, but I want the text to be hidden automatically until it is clicked on with a button. I've looked it up and I can't find how to do this. I figured it should be easy, and I have this part
<h4 id="text1">This is some toggleable text</h4>
$(document).ready(function(){
$("#button1").click(function(){
$("#text1").toggle();
});
});
Which works fine as a regular toggle, but this leaves the text there until first clicked on.
Codepen: https://codepen.io/anon/pen/bYYeEB
The jQuery show,hide and toggle functions simply alter the CSS display property to have either display: block; or display: none;.
To start with your element hidden just set the style attribute style="display:none;".
$(document).ready(
function(){
$("#button1").click(toggle);
}
);
function toggle() {
$("#text1").toggle();
}
toggle();
Calling toggle at the bottom will auto hide the element. This still isn't the greatest since the element will show until this code runs.
But you can always change the HTML to read like this:
<h4 id="text1" style="display:none">This is some toggleable text</h4>
Then you don't need to call toggle the first time.
<script>
$(document).ready(function() {
$("#text1").css("display", "none");//you just have to add this line
$("#button1").click(function() {
$("#text1").toggle();
});
});
</script>

Add active state to simple jQuery accordion

I've got this simple accordion jQuery script that's almost there with what I need it for, but I'm struggling with one last thing. The animated bits work fine - i.e. if the corresponding content block is closed, it slides open, and vice versa.
Here's the jQuery code:
$('.accordion-heading').click(function(){
$(this).next().slideToggle(300);
$('.accordion-content').not($(this).next()).slideUp(300);
$('.accordion-heading.active').removeClass('active');
$(this).addClass('active');
});
I want to have an 'active' class on the heading, but I need it to be removed if the same element is clicked twice. At the moment, everything works fine if a non-active heading is clicked. If an already-active heading is clicked again, however, the content block collapses correctly but the heading retains its 'active' class.
All you need to do is remove the .active class from elements that aren't the current element (you can use the same $.not() method you are currently on another element), then $.toggleClass() the .active class on the clicked element.
$('.accordion-heading').click(function(){
$(this).next().slideToggle(300);
$('.accordion-content').not($(this).next()).slideUp(300);
$(this).toggleClass('active');
$('.accordion-heading').not($(this)).removeClass('active');
});
.accordion-content {
display: none;
}
.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accordion">
<div class="accordion-heading">heading</div>
<div class="accordion-content">body</div>
<div class="accordion-heading">heading</div>
<div class="accordion-content">body</div>
<div class="accordion-heading">heading</div>
<div class="accordion-content">body</div>
</div>
Instead of Adding the class and removing the class I suggest using .toggleClass() this way if the element has the class it will remove it and if it doesn't it will add it. If you want to have one of the accordions open manually give it the active class, and let your JS do the rest.
You could use 'toggleClass()' but I find its better to be more specific by checking if the item that was clicked has the class active. This way you can branch out and do other functions depending on the state:
$('.accordion-heading').click(function(){
var theHeading = $(this);
var theContent = theHeading.next();
var slideTimer = 300;
if(theHeading.hasClass('active')) {
$('.accordion-heading.active').removeClass('active').next().slideUp(slideTimer);
theContent.slideDown(slideTimer);
$(this).addClass('active');
} else {
theContent.slideUp(slideTimer);
$(this).removeClass('active');
}
});

if i clone an element, when i customize (css) that element how can customize also the element cloned?

If i clone an element, then if i want to customize that element (by id) how can customize also the element cloned ?
What i tried:
<div id="A"> //the element that will be clone
</div>
<div id="box" style="margin-top: 50px"> //into this box
</div>
CSS
#A{
width: 100px;
height: 100px;
background: #000;
}
JS
$('#A').clone(true).appendTo('#box');
$('#A').css('background','#ff0000');
//i want to get red background also to element cloned, infact only the true original element change color :/
This is jsfiddle: https://jsfiddle.net/t90ptkcz/1/
I hope that this is possible and you can help me. Thanks a lot and sorry for my english :)
ID # selector finds the unique single element from DOM though multiple elements having same ID present in DOM but class . selector used to get group of elements,having the same class name
<div id="A" class="someClass" > //the element that will be clone
</div>
<div id="box" style="margin-top: 50px"> //into this box
</div>
JS
$('#A').clone(true).appendTo('#box');
$('.someClass').css('background','#ff0000');
I prefer the answer from #shu and however I am not sure in which scenario this could be helpful it is possible to achieve exactly what you want by implementing a jQuery plugin with two methods:
$.fn.cloneAndRemember - will clone an element and store both the source element and its clone (or clones) into a dictionary
$.fn.withClones - will give you a jQuery object collection which includes a selected element and all its clones (retrieved from the dictionary)
The use case would then look like this:
$('#A').cloneAndRemember(true).appendTo('#box');
$('#A').withClones().css('background','#ff0000');

Make :focus change css of another class

Let's say i have the following code:
HTML
<div class="container">
<input class="myAwesomeInputBox">
</div>
CSS
.input [type=text]:focus > .//ANY CLASS SOMEWHERE ON THE WEBSITE{
//Some sweet CSS.
}
Obviously this code doesnt work. I want some specific css to get executed when there is focus on my inputbox. Is this at all possible?
I'm not specificly looking for html/css only solutions. Any solution that can achieve this is welcome.
My code above is just an extremely simple example. My question is really simple. Is it possible to change styling on ANY element on your website using the :focus on an input box.
Using pseudo-classes (such as :hover or :focus) to modify other elements can only be done if the other elements are siblings or children of the element which has the pseudo-class. That's because CSS child/sibling selectors are fairly restrictive.
You can use the > selector to select a direct child, and the + selector to select a direct sibling. For example, if you have the following HTML:
<form>
<input type="text" />
<input type="submit" />
</form>
<p class="arbitrary">
This is an arbitrary element. It is neither a child nor sibling of
the text field. It cannot be selected as a result of a pseudo-class
action on the textfield using CSS, but can be selected using
client-side scripting such as JavaScript.
</p>
You could style the button when the text field has focus (because it is a direct sibling of the text field), but there is no possible way to style the arbitrary paragraph as a result of the text field receiving focus (because it is neither a child nor sibling, it is the sibling of a parent) without using client-side scripting (JavaScript, jQuery, etc.).
This CSS would style the submit button, and can be altered to select any direct or indirect child or sibling:
input[type="text"]:focus + input[type="submit"] {
/* some sweet CSS */
background-color:green;
}
Using Javascript, of course, you have much greater flexibility. The focusin and focusout events can be used to toggle CSS classes. Here's an example that demonstrates both the CSS and JavaScript techniques of achieving this.
function setFocused() {
document.querySelectorAll('.arbitrary').forEach((result) => {
result.classList.add('focused');
});
}
function unsetFocused() {
document.querySelectorAll('.arbitrary').forEach((result) => {
result.classList.remove('focused');
});
}
document.querySelectorAll('input[type="text"]').forEach((result) => {
result.addEventListener("focusin", setFocused);
result.addEventListener("focusout", unsetFocused);
});
input[type="text"]:focus + input[type="submit"] {
/* some sweet CSS */
background-color: green;
}
.arbitrary.focused {
/* even more sweet CSS */
color: red;
}
<form>
<input type="text" />
<input type="submit" />
</form>
<p class="arbitrary">
This is an arbitrary element. It is neither a child nor sibling of
the text field. It cannot be selected as a result of a pseudo-class
action on the textfield using CSS, but can be selected using
client-side scripting such as JavaScript.
</p>
Here's the jQuery equivalent of the above code, if that's your jam.
$('input[type="text"]').on('focus', function() {
$('.arbitrary').addClass('focused');
});
$('input[type="text"]').off('focus', function() {
$('.arbitrary').removeClass('focused');
});
Note that if you decide you want to do something similar, except using a "hover" trigger rather than "focus", you can use the JavaScript mouseover and mouseout functions, or the jQuery .hover() function which takes two arguments (a handler for entering the hover and another for leaving the hover).
Maybe add a ID
<div class="container">
<input class="myAwesomeInputBox" id='myAwesomeId' type="text">
</div>
and add and remove a class like this.
Wont that solve your problem.
$('#myAwesomeId').on({
focus: function () {
$(this).addClass('focused');
},
blur: function () {
$(this).removeClass('focused');
}
});
CSS
input.focused {
border:3px solid blue;
}
FIDDLE
If the element css which you want to change is sibling, you can use like this,
<div class="container">
<input class="myAwesomeInputBox">
<div className="dls-sibling">
</div>
.myAwesomeInputBox:focus ~.dls-sibling {
&::before {
transform: scale(1);
border-color:red;
}
}

Categories