vanilla js remove id box [duplicate] - javascript

This question already has answers here:
Onclick event not firing on jsfiddle.net [closed]
(2 answers)
Closed 5 years ago.
I know how to do it with JQuery but I would like to remove a box with an onClick element (x) with vanilla JS. According to this I need to remove child element. As far as to this is my attempt:
function remove() {
var element = document.getElementById("box");
element.parentNode.removeChild(element);
}
#box {
background-color: lightgrey;
color: white;
width: 20em;
height: 20em;
border: 25px solid green;
padding: 25px;
margin: 25px;
}
.remover {
font-size: 10em;
align
}
<div id="box">
<div id="removeBox" onclick="remove()">
<span class="remover">x</span>
</div>
</div>
Would you mind to help me to remove whole box with just clicking the 'x'?
jsfiddle
Thank you so much

Don't use onclick, it's bad practice, here is why:
mixes code and markup
code written this way goes through eval
runs in the global scope while directly written functions run in user scope
Use event binding like:
document.getElementById("box").addEventListener('click', function() {
var element = document.getElementById("box");
element.parentNode.removeChild(element);
});
Here is an entire fiddle:
fiddle

Related

Compared with Vanilla JavaScript, does jQuery simplify selecting related nodes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
In my experience, jQuery simplifies DOM navigation immensely as when compared to using pure JavaScript.
Suppose I have two elements #parentA and #parentB and both these two elements have similar children nodes .x .y .z.
Often times, when I use JavaScript without jQuery, if I want to select #parentA's .x I end up accidentally selecting both #parentA .x as well as #parentB.x.
I suppose this is more of a backend developer's therapy session where I am just letting out my frustration with JS rather than asking a question.
The main reason why I am trying to avoid using jQuery is that I am trying to keep the website page weight as low as possible. What would the JavaScript equivalent be of the jQuery code I have below?
HTML
<h2>Colour 1</h2>
<div id="hairColor" class="color-palette">
<ul>
<li style="background: #fc4c4f;"></li>
<li style="background: #4fa3fc;"></li>
<li style="background: #ecd13f;"></li>
</ul>
</div>
<h2>Colour 2</h2>
<div id="skinColor" class="color-palette">
<ul>
<li style="background: #fc4c4f;"></li>
<li style="background: #4fa3fc;"></li>
<li style="background: #ecd13f;"></li>
</ul>
</div>
SCSS
.color-palette {
background: #384047;
min-height: 60px;
margin: 0 auto;
width: 100%;
border-radius: 5px;
overflow: hidden;
ul {
list-style: none;
margin: 0;
float: left;
padding: 10px 0 20px;
width: 100%;
text-align: center;
li {
display: block;
height: 54px;
width: 54px;
border-radius: 60px;
cursor: pointer;
border: 0;
box-shadow: 0 3px 0 0 #222;
display: inline-block;
margin: 0 5px 10px;
}
.selected {
border: 7px solid #fff;
width: 40px;
height: 40px;
}
}
}
JS
$(".color-palette").on("click", "li", function(){
$(this).siblings().removeClass("selected");
$(this).addClass("selected");
color = $(this).css("background-color");
});
// What would the equivalent code be using vanila JavaScript?
// var colors = document.querySelectorAll("#hairColor ul li");
To make that without something like jQuery, you'll need a few iterators (a for loop or something), is 100% doable and is not that hard but beware, is a larger piece of code.
What that code is doing is assigning the click event to the color-palette container and filtering by the target element to match the LI, if you want you can simplify it by just assigning the click to the li directly and check on the parent.
This is a starting point to replicate the same behavior:
document.querySelectorAll('.color-palette').forEach((palette) => {
palette.addEventListener('click', (e) => {
e.target.parentNode.querySelectorAll('li').forEach((li) => {
li.classList.remove('selected');
})
if (e.target.tagName.toLowerCase() !== 'li') {
return;
}
e.target.classList.add('selected');
})
})
This could be simplified a bit but is a draft and should be working.
Something like this should do the trick:
let triggers = document.querySelectorAll('li')
triggers.forEach(el => {
el.addEventListener('click', () => {
[...triggers].map(x => x.classList.remove('selected'))
el.classList.add('selected');
let color = el.style.backgroundColor;
})
})
First, you add eventlisteners to each li element, and when clicking on one, you create an array of the elements by using the spread ... operator. Chain this array afterwards with the map operator to remove the selected class. And finally, you simply add the selected class to the element you've clicked.

How do I change the Background Color and Text Color in a Box?

I am somewhat new to Javascript/HTML. Recently I've been given a project to align boxes of Avengers characters using CSS or HTML. Here is an image of what the website should look like:
Now I've gotten the CSS part of the code done: defining the boxes for the images, headings/titles of the characters, and their description (in the main body). For the javascript part, the box of the name of the character should change color when the mouse hovers over it, and change back to its original color once removed. For this matter, I will use a portion of my code for the heading, from Iron Man.
CSS:
.ironManHeading { <!-- iron man's heading (goes under image box) -->
left:0px;
width: 250px;
position: relative;
background-color: #999999;
padding: 10px;
text-align: center;
border: 1px solid black;
}
Javascript:
function mouseIM(){ //onmouseover event: heading changes to red background and white text
document.getElementsByClassName("ironManHeading").bgColor = 'red';
document.getElementsByClassName("ironManHeading").fontcolor = 'white';
} // MOUSE EVENTS FOR IRON MAN
function noMouseIM(){ //onmouseout event: heading changes back to normal colors
document.getElementsByClassName("ironManHeading").style.bgColor = '#999999';
document.getElementsByClassName("ironManHeading").style.fontcolor = 'black';
}
And here is the code from the body:
<h1 class = "ironManHeading" onmouseover = "mouseIM" onmouseout = "noMouseIM">IRON MAN</h1>
This is what I've tried, but the colors stay the same as from the image from above. Am I doing something wrong, or am I missing something? I haven't gotten the hang of declaring classes, so I'm not sure if it's something to do with document.getElementsByClassName.
You can achieve the desired behavior with css only like this:
.ironManHeading:hover {
background-color: red;
color: white;
}
If you still want to use Javascript with onmouseover and onmouseout events here's a similar example:
function onMouseOver(elem) {
elem.style.backgroundColor = "red";
elem.style.color = "white";
}
function onMouseOut(elem) {
elem.style.backgroundColor = "#999";
elem.style.color = "black";
}
div {
background-color: #999;
}
<div onmouseover="onMouseOver(this)" onmouseout="onMouseOut(this)">Here's a test</div>
Why your event handlers don't work?
It's simply because you call the methods like this:
onmouseover = "mouseIM"
but you have to call it like this:
onmouseover="mouseIM()"
that's the way to assign event handler function to a HTML event attribute.
Additionally, you can pass a reference to the object that invoked the function with:
onmouseover="mouseIM(this)"
This spares the need to use the selector of the calling element with document.getElementById(), getElementsByClassName() or querySelector() and gives you the flexibility to use the event handler for other elements too. So in your case you can call the same function for each avenger box by calling the event handler with this parameter. See how I used the elem parameter in my event handler functions above.
Consider using css pseudo-classes as #chrisbyte mentioned. In this case, you shouldn't need javascript to perform what you need, attached link below for you to learn more!
https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
.ironManHeading :hover{
background-color: red;
color: white;
}
With css, you can declare a :hover event that does the same thing as mouseover and mouseout in javascript. Something like:
.ironManHeading { <!-- iron man's heading (goes under image box) -->
/* your original definition */
}
<!-- this is the hover event -->
.ironManHeading:hover {
background-color: red;
color: white;
}
Working example (does not require any javascript, everything is handled by css):
.Heading {
left:0px;
width: 250px;
position: relative;
background-color: #999999;
padding: 10px;
text-align: center;
border: 1px solid black;
}
.Heading:hover {
background-color: red;
color: white;
}
<h1 class = "Heading">IRON MAN</h1>
<h1 class = "Heading">CAPTAIN AMAERICA</h1>
<h1 class = "Heading">THOR</h1>
<h1 class = "Heading">BLACK WIDOW</h1>

Move selected objects from one place to another and back again to original position javascript

I am making a keyword selector in where a user selects one or more keywords from one box. Those keywords that are selected are then taken out of the original box and put into the one alongside it, displaying the selected keyword.
I wish to store the keyword elements in an array but i am having trouble figuring out how the user would actually click on the element and display it in the opposite box. The only way I seem to be making any progress is with onclick() functions etc... for the individual elements but thats not what I am looking for.
Is it possible to move these elements from within their contained div to the the empty box div ??. Any advise or responses on this would be appreciated, attached is a code snippet to get a better grasp on the problem. Thanks everyone.
var kwords = [
"audi",
"bmw",
"chevrolet",
"honda",
"mercedes",
]
function car1() {
document.getElementById("inner").style.color = 'blue';
}
#boxleft {
border: 5px solid blue;
background-color: gray;
height: 250px;
width: 250px;
margin-bottom: 20px;
float: left;
}
#boxright {
border: 5px solid blue;
background-color: gray;
height: 250px;
width: 250px;
margin-bottom: 20px;
float: left;
display: inline;
}
#inner {
color: red;
}
<div id="boxleft">
<div id="inner" onclick="car1();">audi</div>
<div id="inner1">bmw</div>
<div id="inner2">chevrolet</div>
<div id="inner3">honda</div>
<div id="inner4">mercedes</div>
</div>
<div id="boxright"></div>
You can attach click listener to many elements at once. Take a look at this codepen.
What is happening here:
document.querySelectorAll('.keyword') looks for all elements with keyword class in the document (take a look how I've changed the HTML section)
Inside forEach loop, line element.addEventListener('click', toggleKeyword) adds click listener to every found element (which is equivalent to manually assigning onClick attribute)
Now when you click on a keyword, toggleKeyword function is executed:
var element = event.target; is the element you clicked
boxLeft and boxRight variables are these two divs with boxLeft and boxRight ids
var newParent = element.parentNode.id === 'boxleft' ? boxRight : boxLeft; this line checks which the new parent element should be, if you clicked on div inside the leftbox it should go to the rightbox and vice versa.
Finally we remove element from it's current parent and add to the opposite one.

I don't understand how to use document.getElementById(‘id’).onclick

I'm learning javascript right now and I am just building a simple menu that will show when the nav button is clicked.
I don't understand how to use the document.getElementById(‘id’).onclick when in a separated js file that is linked to my html. Reading around I think I understand that my problem is that you cannot call onclick out the blue because the DOM element are not yet defined.. or something alone those line. I just don't understand then how to proceed.
If I add within my button html tag onclick="function()" it works, but it don't when I add it within my separate js file. I'm using the W3school tutorial found here.
Here is my code
<nav>
<button class="nav-button" id="nav">
<div class="menu-button"></div>
<div class="menu-button"></div>
<div class="menu-button"></div>
</button>
<div class="dropdown-menu" id="dropdown">
Hello
Hello
Hello
</div>
</nav>
.nav-button {
background: none;
border: none;
margin-left: 1em;
padding-top: 12px;
cursor: pointer;
}
.menu-button {
background-color: #fff;
width: 30px;
height: 4px;
margin-bottom: 5px;
border-radius: 5px;
}
.dropdown-menu {
margin-top: 7px;
width: 100px;
background-color: #fff;
display: none;
}
.showDropDown {
display: block;
}
function showDropDown() {
document.getElementById('dropdown').classList.toggle("showDropDown");
}
document.getElementById("nav").onclick = function showDropDown()
Here is a codepen
Thanks for your help!
just instead of
document.getElementById("nav").onclick = function showDropDown()
replace it with
document.getElementById("nav").onclick = showDropDown
because the onclick accepts function and you'r already defined this function
1.create myjavascript.js file in same folder where your page html is.
2.copy the javascript code in myjavascript.js "only code not tag <script></script>"
4.paste this at the end of your html page
<SCRIPT language="javascript" src="myjavascript.js" type="text/javascript"></SCRIPT>
This is the way to reference your code javascript in your html file.
It will be much easier to work with jquery than plain javascript.
Here how you are calling showDropDown function is wrong
change function showDropDown to
showDropDown
Better you can make the closure at the button click event like
let btn = document.getElementById("nav");
let toggleIt = document.getElementById('dropdown');
btn.onclick = function(){
toggleIt.classList.toggle("showDropDown");
};
Having it in a separate js file should work you just need to import the js file using the script tag. You should probably do this at the end of the HTML to guarantee that the js is ran after the DOM is loaded.
Update Your missing the brackets around the function call:
document.getElementById("nav").onclick = function() { showDropDown(); };

Change style of an element when focusing a non-related element [duplicate]

This question already has answers here:
Affecting parent element of :focus'd element (pure CSS+HTML preferred) [duplicate]
(2 answers)
Closed 7 years ago.
When I focus the input text element, I want to change the background color of the submit button.
<input id="submit-element" type="submit">
<span><input id="text-element" type="text"></span>
However, based on the current setup of the elements, I believe the span blocks them from being sibling elements and being able to use the ~ selector.
So how can I accomplish this? Is JavaScript necessary?
With current DOM you're forced to use javascript. Below there is a jQuery solution.
$('input#text-element').focus(function() {
$('input#submit-element').css('color', 'red');
});
$('input#text-element').focusout(function() {
$('input#submit-element').css('color', 'black');
});
You have to use JavaScript since the DOM is restricted from CSS. Try the following, which uses the onblur and onfocus input parameters:
.button {
padding: 2px 4px;
font: 13px sans-serif;
text-decoration: none;
border: 1px solid #000;
border-color: #aaa #444 #444 #aaa;
border-radius: 5px;
color: #000
}
New Element
<span><input id="text-element" type="text" onfocus="document.getElementById('submit-element').style.backgroundColor = 'red'" onblur="document.getElementById('submit-element').style.backgroundColor = 'inherit'"></span>
Try this..
HTML
<input id="submit-element" type="submit">
<input id="text-element" type="text">
Javascript
document.getElementById("text-element").addEventListener("focus", changeSubmitF);
function changeSubmitF(){
document.getElementById("submit-element").style.backgroundColor = "#f4f4f4";
}
document.getElementById("text-element").addEventListener("blur", changeSubmitB);
function changeSubmitB(){
document.getElementById("submit-element").style.backgroundColor = "transparent";
}
Check out this Fiddle

Categories

Resources