Let me be frank, I have no idea how javascript works. I was hoping someone could show me how to get this to actually function.
What I’m trying to do is use the element’s class name to change it’s display to ‘none’, and the next sibling element’s display to ‘block’ on click. I’m using class name because I’d like this to be applicable to whatever element has that class. Someone please tell me what I did wrong?
CSS
.box {
position: relative;
top: 0px;
width: 150px;
height: 150px;
color: #fff;
cursor: pointer;
}
#box {
background-color: green;
}
#box2 {
display: none;
background-color: blue;
HTML
<div class="box" id="box" onclick="myFunction()">
<p>text text text text text</p>
</div>
<div class="box" id="box2">
<p>text text text text text text text text text text</p>
</div>
JS
function myFunction() {
if (element.hasClass("box")) {
this.element.style.display = "none";
nextElementSibling.style.display = "block";
}
}
Sorry if this is dumb, I have no idea what I’m doing.
3
Answers
Let me be
AsyncAwait
, I have some (?) idea how javascript works. I was hoping this could show you how to get this to actually function.Instead of assigning the function inline, in the HTML, I assign it in the js. Then, instead of refrencing the element using
this.element
I can useevent.currentTarget
. This will ensure we are firing the event on the element we assigned the event listener. Now we don’t need to check if it has the desired class.I store the element into a variable, for clarity.
I set the display to none, grab the next element, and change it’s display to block (it’s already block so it doesn’t really change anything).
Hopefully this adds some clarity! If you have any questions, feel free to ask <3
The click event handler created by the HTML parser doesn’t call
myFunction
with any arguments.One way of fixing this is to pass
this
as its argument:where
this
refers to the element with theonclick
attribute.Note adding event handlers in JavaScript is recommended over adding them in HTML. See the addEventListener method to start your research.
If you don’t know how to find elements in JS, have a look at
document
methodsquerySelector
andquerySelectorAll
to start with (there are other methods for finding elements). They can be called on elements as well asdoocument
.In
myFunction
you will need topick up
element
as argument,use the
element.classList.contains
method to see if hasbox
in its [DomTokenList] class list.Code
nextElementSibling
as a property ofelement
to find the required sibling.With the changes:
There’s a lot to learn, happy coding and research. … However, if you have multiple things going wrong and need help, check the
console
tab of developer tools for code errors and attempt to solve them in order of appearance before posting about the first one you couldn’t resolve. 🙂Check these issue, maybe this will improve the coding:
Here I have added the updated code please check: