Reputation: 505
I am a beginner at javascript and I wrote a simple code trying to show/hide a div simply by clicking on another div. If someone can check the code I wrote and correct me I would be really grateful. Thanks in advance.
$('DivBlue').ready(function() {
$('DivRed').on('click', function(){
document.getElementById('DivBlue').style.display = 'block';
});
});
.DivRed{
position:absolute;
top:0;
left:0;
width:15vw;
height:15vw;
background-color:red;
}
.DivBlue{
position:absolute;
display:none;
right:0;
bottom:0;
width:15vw;
height:15vw;
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="DivRed"></div>
<div class="DivBlue"></div>
Upvotes: 1
Views: 7197
Reputation: 894
You are making few mistakes here,
You cant get a div by a class name with document.getElementById()
method. You need to use document.getElementsByClassName()
method.
document.getElementsByClassName()
return a NodeList. You can't apply CSS for a NodeList. So you need to select a Node to apply CSS using document.getElementsByClassName('DivBlue')[0]
To work your code should be changed as
$('DivBlue').ready(function() {
$('DivRed').on('click', function(){
document.getElementsByClassName('DivBlue')[0].style.display = 'block';
});
});
Upvotes: 1
Reputation: 9024
You can do this with the toggle() function in the jQuery library. toggle()
with no arguments is a to shortcut show/hide an DOM element.
Also, it is good practice to use .ready()
on the document instead of an element of the DOM.
So, your JS code should look like:
$(document).ready(function() {
$('.DivRed').on('click', function(){
$('.DivBlue').toggle();
});
});
Upvotes: 4
Reputation: 903
Replace your JavaScript with this and it will surely work.
$(document).ready(function() {
$('.DivRed').click(
function() {
$('.DivBlue').toggle();
});
});
Upvotes: 2
Reputation: 166
Toggle does the trick in jQuery:
$(document).ready(function() {
$('.DivRed').on('click', function() {
$('.DivBlue').toggle();
});
});
Upvotes: 2