the ID is taking over my class when im using Javascript - javascript

I've been sitting with this problem for like 2 hours. What I'm trying to make is a website where you push a button and it changes color. I know this can be done with CSS, but I'm not interested in that.
The main problem is that when I push the button, nothing happens.. However, if I remove the ' #sug from the css' everything works perfectly... So what I want to do, is to make the layout very basic at the beginning, so there's nothing to it, except like the black background, and when I push the buttons it should switch..
Also, I know you can implement onclick in the button tag, but that's not what I'm going for either. I want to know WHY this happens and how I can resolve this problem.
Here's my javascript, CSS and HTML code:
window.onload = setUp;
function setUp() {
document.getElementById("normal").onclick = setNormalStyle;
document.getElementById("crazy").onclick = setCoolStyle;
document.getElementById("insane").onclick = setInsaneStyle;
}
function setNormalStyle() {
var messageBox = document.getElementById("sug");
messageBox.className = "normal";
}
function setCoolStyle() {
var savingTheSecondVar = document.getElementById("sug");
savingTheSecondVar.className = "cool";
}
function setInsaneStyle() {
var savingTheThirdVar = document.getElementById("sug");
savingTheThirdVar.className = "insane";
}
#sug {
background-color: black;
}
.normal {
height: 500px;
background-color: blue;
color: white;
padding: 30px;
margin: auto;
width: 500px;
}
.insane {
height: 500px;
background-color: green;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
.cool {
height: 500px;
background-color: red;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="Struktur.css" />
<script type="text/javascript" src="struktur.js"></script>
<title>My first Javascript project</title>
</head>
<body>
<div id="sug" class="cool insane normal">
<header>
<h1> Welcome to this Javascript site! </h1>
</header>
<section>
<p>
text
</p>
</section>
<button type="button" id="normal">First style</button>
<button type="button" id="crazy">Second style</button>
<button type="button" id="insane">Third style</button>
</div>
</body>
</html>

The problem is your CSS.
#sug{
background-color: black;
}
Overrides the background-color of your classes because it is a more specific selector (i.e. an id selector).
change the rest of your classes in the css to include the id like
#sug.normal, #sug.insane, #sug.cool etc.
Here is a nice article on CSS specificity to help you understand more: https://css-tricks.com/specifics-on-css-specificity/

That's because an id has preference over a class. You will need to specify it like this:
#sug.cool { background: red; }
etc.

You are not removing the background-color provided by the #sug id in CSS onClick() events of the buttons.
Id has more preference over classes
It is a good habit to use below code as classes has spaces between them and it can be used if you want to add more than one class.
messageBox.className += " " + "normal";

Related

addEventListener/querySelector/Toggle - need help changing color but deselecting other tab

// Desktop View
const content1 = document.querySelector('#tab-1');
content1.addEventListener('click', (e) => {
document.querySelector('.dropdown-1').classList.toggle('hide');
document.querySelector('.dropdown-2').classList.remove('hide');
document.querySelector('.dropdown-3').classList.remove('hide');
document.querySelector('.fitguide').classList.toggle('darkBG');
document.querySelector('.fitguide a').classList.toggle('lightText');
});
The above is my JavaScript for this section I am having issues with. When I select a tab, the background and text colors change, as they are supposed to, but when I select another tab, the previously selected tab does not deselect and change back to normal. I am talking about the last two toggle lines of code here. My CSS for them :
.darkBG {
background: black;
}
.lightText {
color: white;
}
I have tried a lot of things to try and fix this, but I just keep getting no text, only background change. I want to do it with JavaScript but can do it in the CSS if necessary. Does anybody have fresh eyes, experience with this issue?
We are missing the HTML part. However, we can play with this. I think it's somethin like this that you would like.
const content1 = document.querySelector('#tab-1');
content1.addEventListener('click', (event) => {
let targetElement = event.target;
for (let element of content1.children) {
if (element === targetElement) {
element.classList.remove("deselected");
element.classList.add("selected");
continue;
}
element.classList.add("deselected")
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST STACKOVERFLOW</title>
<style>
.darkBG {
background: black;
}
.lightText {
color: white;
}
.dropdown-1{
border: 1px solid black;
}
.dropdown-2{
border: 1px solid black;
}
.dropdown-3{
border: 1px solid black;
}
.selected{
background-color: aquamarine;
}
.deselected{
background-color: black;
}
#tab-1 div{
width: 50px;
height: 50px;
margin: 5px;
}
</style>
</head>
<body>
<div id="tab-1">
<div id="1" class="dropdown-1"></div>
<div id="2" class="dropdown-2"></div>
<div id="3" class="dropdown-3"></div>
</div>
<script src="./stackoverflow.js"></script>
</body>
</html>
Click on any of the squares that you will notice that the css will be applied to the element that you clicked.
Be aware in the targetElement that is the clicked element. There are many solutions for this case, but it's a begin

Why isn't fadeIn() working?

My HTML Code is :
<!DOCTYPE html>
<html>
<head>
<title>Furry Friends Campaign</title>
<link rel="stylesheet" type="text/css" href="styles/my_style.css">
</head>
<body>
<div id="clickMe">Show me the the Furry Friend of the Day</div>
<div id="picframe">
<img src="images/furry_friend.jpg" alt="Our Furry Friend">
</div>
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#clickMe").click(function()
{
$("img").fadeIn(1000);
$("#picframe").slideToggle("slow");
});
});
</script>
</body>
</html>
The accompanying CSS looks like:
#clickMe {
background: #D8B36E;
padding: 20px;
text-align: center;
width: 205px;
display: block;
border: 2px solid #000;
}
#picframe {
background: #D8B36E;
padding: 20px;
width: 205px;
display: none;
border: 2px solid #000;
}
The slideToggle works perfectly, but for some reason, the image doesn't fade in. I've tried setting the duration to longer periods, but that yields the same results. Can someone point out what's wrong with this code? I'm using the latest version of Chrome.
UPDATE: I tried running the example code of the book I was using, which uses jquery-1.6.2.min.js and using that version of jQuery, the code works perfectly. Is this some error on jQuery's part? Or is the new way that things will be done now?
Since jQuery 1.8, fadeIn no longer initially hides the image, so trying to fade in an image which is visible or doesn't have display set to none won't lead to anything.
To fade in, you should hide it first. Initially it's not hidden, since children don't inherit display CSS property, and you have set it to none only on #picframe, the parent of img. Just add $("img").hide(); on ready. This will make it work.
Since it looks like you need to fade it in / out with each click, you could do the following instead of $("img").fadeIn(1000):
if($("img").is(":hidden")) $("img").fadeIn(1000);
else $("img").fadeOut(1000);
Demo below.
#clickMe {
background: #D8B36E;
padding: 20px;
text-align: center;
width: 205px;
display: block;
border: 2px solid #000;
}
#picframe {
background: #D8B36E;
padding: 20px;
width: 205px;
display: none;
border: 2px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="clickMe">Show me the the Furry Friend of the Day</div>
<div id="picframe">
<img src="images/furry_friend.jpg" alt="Our Furry Friend">
</div>
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//$("img").hide();
$("#clickMe").click(function() {
$("img").fadeIn(1000);
$("#picframe").slideToggle("slow");
});
});
</script>
Somehow, img didn't inherit the display:none in #picframe div. Here's the fix: https://jsfiddle.net/69rLha7e/1/
There is a "timing" consideration while playing with multiple animations a time.
In this CodePen, I used diferent timing for fadeIn, fadeOut and toggleSlide.
And you have to check the display state in order to decide to fade in or out.
$(document).ready(function(){
$("#clickMe").click(function(){
console.log( $("img").css("display") ) ;
if( $("img").css("display")=="inline" ){
$("img").fadeOut(400);
}else{
$("img").fadeIn(800);
}
$("#picframe").slideToggle(400);
});
});

Fix navbar to top of page when scrolling

I'm trying to make a navbar similar to the one on Linus Tech tips (https://linustechtips.com/main/) for a school assignment. I'm at the real basic level of Javascript and I cooked up a pinnable navbar but when I made it there was no banner above it. Now there is a banner above it and I don't know how to make the navbar push to the top when I start scrolling.
Here is my HTML:
<div class="navContainer">
<div class="topBanner">
<img src="images/topbanner.png" id="topBannerimg"/>
</div>
<div id="navbar">
<button onclick="pinfunc()"><i id="pin" class="fa fa-thumb-tack fa-2x navButton" id="pinbtn" aria-hidden="true"></i></button>
</div>
</div>
Here is my Javascript:
var pinned = 1;
console.log(pinned);
function pinfunc() {
if (pinned == 1) {
document.getElementById("navbar").style.position= "relative";
document.getElementById("pin").style.color = "black";
document.getElementById("pin").style.transform = "rotate(0deg)";
pinned=0;
}
else if (pinned == 0) {
document.getElementById("navbar").style.position="fixed";
document.getElementById("pin").style.color = "red";
document.getElementById("pin").style.transform = "rotate(270deg)";
pinned=1;
}
}
And here is my CSS:
body{
margin: 0 auto;
}
.navContainer{
width: 100%;
margin: 0 auto;
}
#topBannerimg{
width: 100%;
margin: 0;
display:block
}
.navButton{
height: 25px;
width: 25px;
}
.fa-thumb-tack{
font-size: 50px;
color: red;
transform: rotate(270deg);
}
.container{
height: 1000px;
width: 90%;
margin: 0 auto;
}
#navbar{
height: 50px;
width: 100%;
position: fixed;
margin: 0 auto;
background-color: #D35300;
}
#nav{
background-color: #D35300;
height: 50px;
}
I'm just looking to create a basic one of the LTT forum - no need for the toggle button to fade out or anything.
This is my first post so I'm not 100% sure how to do stuff.
Thanks in advance.
If you are allowed to use external JS or CSS libraries, then try the Affix plugin for bootstrap. (link: http://www.w3schools.com/bootstrap/bootstrap_affix.asp). It makes what you are trying to accomplish simple.
If you are not allowed to use any external libraries then, I suggest you read this: http://getbootstrap.com/javascript/#affix-examples and try to implement it yourself.
Good Luck!
So I got it working with the following HTML, JS, and CSS files:
HTML
<html>
<head>
<link rel="stylesheet" href="path/to/font-awesome.css/file" type="text/css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<!-- Custom CSS File Below -->
<link href="/path/to/custom/css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="topBanner">
<img src="images/topbanner.png" id="topBannerimg"/>
</div>
<div id="navbar" data-spy="affix" data-offset-top="100">
<button onclick="pinfunc()"><i id="pin" class="fa fa-thumb-tack fa-2x navButton" aria-hidden="true"></i></button>
</div>
<div id="SpaceFiller"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="path/to/custom/js/file"></script>
</body>
</html>
The key things to learn from this HTML are the loading the JS files at the bottom of the body tag so the page can load first, and the order in which the CSS and JS files are loaded. The SpacFiller div is just there to enable scrolling. Also, note that I removed your navbar-container as it didn't seem necessary.
Javascript
var pinned = true;
function pinfunc() {
var $pin = $("#pin");
var $navbar = $("#navbar");
if (pinned) {
$pin.css({
'color': 'black',
'transform': 'rotate(0deg)'
});
console.log("not pinned")
$(window).off('.affix');
$navbar.removeClass('affix affix-top affix-bottom');
$navbar.removeData("bs.affix");
pinned = false;
} else {
$pin.css({
'color': 'red',
'transform': 'rotate(270deg)'
});
$(window).on('.affix');
$navbar.addClass('affix');
$navbar.affix({
offset: 100
});
pinned= true;
}
}
This JS uses jQuery Selectors (which actually uses sizzle.js I believe) to get access to HTML elements via their IDs. Using the returned jQuery object, the function sets the appropriate CSS and then toggles affix using functions you can read about here: http://getbootstrap.com/javascript/#affix, https://api.jquery.com/removeclass/, https://api.jquery.com/jQuery.removeData/, http://api.jquery.com/off/. Also, you were using 0 and 1 for the pinned values but it is good practice to use boolean values (true and false) as shown.
CSS
body{
margin: 0 auto;
}
.affix {
top: 0;
width: 100%;
}
.affix + .container-fluid {
padding-top: 70px;
}
#topBannerimg{
width: 100%;
margin: 0;
display:block;
height: 100px;
top: 0px;
}
.navButton{
height: 25px;
width: 25px;
}
.fa-thumb-tack{
font-size: 50px;
color: red;
transform: rotate(270deg);
}
#navbar{
height: 50px;
width: 100%;
margin: 0 auto;
background-color: #D35300;
}
#SpaceFiller {
height: 10000px;
background-color: darkgreen;
}
I think the CSS is self-explanatory, but if it is unclear go ahead and ask for clarification. Hope this helps! :D
Edit: You can also put the onclick attribute on the i tag itself and get rid of the button wrapper if you want to get rid of the white button background.

Simple Add class with Javascript

I've this code :
jQuery(document).ready(function($) {
document.getElementById('HAVEATESTHERE').className = "newClass";
}
I want to add a class to #HAVEATESTHERE in javascript, it does not work
Am I missing something ?
You can use classList.add method:
document.getElementById('HAVEATESTHERE').classList.add('first','second', ... );
Also, please make sure you add your class after DOM is rendered.
Take into account, that element.className = 'someClass' will override existing classes with someClass.
elementid is your element`s id and yourclass is that what class do you want add this element.
jQuery(document).ready(function($) {
$('#elementid').addclass('yourClass');
}
Code is fine, see this demo
Ensure that it is either
Added in the window.onload section
window.onload = function(){
document.getElementById('HAVEATESTHERE').className = "class1";
};
if there are already some classes for this element (as suggested by your updated OP), then use classlist to add a new class to that list
document.getElementById('HAVEATESTHERE').classList.add("class1");
- Or the script section is added at the end of body after all the markup is already loaded.
make sure you don't have duplicate IDs for divs. Check this:
function myFunction() {
document.getElementById("myDIV").className = "myclass";
}
.myclass {
width: 200px;
height: 100px;
background-color: blue;
text-align: center;
color: white;
margin-bottom: 10px;
}
<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 100px;
background-color: coral;
text-align: center;
font-size: 25px;
color: white;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to add a class for div.</p>
<div id="myDIV">
Sample div
</div>
<button onclick="myFunction()">Add Class</button>
</body>
</html>
Basically you are trying to mix JavaScript inside jQuery function. Please take care of that. And if you are only using jquery then please use your code
As in this formate
$(document).ready(function(){
$('#HAVEATESTHERE').addclass('newClass');
}
use addclass() function to add class to your div.
with simple js please try to use anonymous function like this
(function(){
var d = document.getElementById("HAVEATESTHERE");
d.className = " newClass";
})();

document.querySelectorAll length is always 0

I'm trying to create some draggable boxes in javascript. I decided to make an empty class "draggable" in CSS and a "box" class. The code is as follows:
<!DOCTYPE html>
<html>
<head>
<style>
.draggable
{
}
.box
{
position: absolute;
width: 80px; height: 60px;
padding-top: 10px;
text-align: center;
font-size: 40px;
background-color: #222;
color: #CCC;
}
</style>
</head>
<body>
<div class="draggable box">1</div>
<div class="draggable box">2</div>
<div class="draggable box">3</div>
<script>
var draggableStuff = document.querySelectorAll('draggable');
var tabLength = draggableStuff.length;
alert(tabLength);
</script>
</body>
The problem is that tabLength is always zero. I want to get an array filled with all draggable stuff. I'm new to javascript. What have I missed here?
You want to select elements by class, so don't forget about the dot:
var draggableStuff = document.querySelectorAll('.draggable');
Another option is to use document.getElementsByClassName:
var draggableStuff = document.getElementsByClassName('draggable');
I came across this situation. Although it is too old post I would like to help people with my answer:
To select all the elements (no matter what it is, it may be div, span, h1, etc...) with particular attribute
Without value?:
var dragables = document.querySelectorAll('[draggable]');
With value?:
var dragables = document.querySelectorAll('[draggable="true"]');

Categories