Switch animation through 'If Statement' in jQuery - javascript

I have some code in jQuery in which I want to make a switch animate on or off by clicking on a div. Here is the code. When I test it, it doesn't work. However if I remove toggle = true on line 7, it just works one way and I can't turn it back off.
$(document).ready(function () {
$("#switch").click(function () {
var toggle = false;
if (toggle == false) {
$("#circle").css("left", "27px");
$("#white_rect").attr("src", "green_rect.png");
toggle = true;
}
if (toggle == true) {
$("#circle").css("left", "1px");
$("#white_rect").attr("src", "white_rect.png");
toggle = false;
}
});
});

You need to declare the toggle variable outside of the click handler... else in every click call the variable will get reinitialized so the value of the variable will always be false.
$(document).ready(function () {
//declare it here
var toggle = false;
$("#switch").click(function () {
if (toggle == false) {
$("#circle").css("left", "27px");
$("#white_rect").attr("src", "green_rect.png");
toggle = true;
//also don't use a separate if block here as it will be affected by the execution of the above if block
} else {
$("#circle").css("left", "1px");
$("#white_rect").attr("src", "white_rect.png");
toggle = false;
}
});
});
$(document).ready(function () {
//declare it here
var toggle = false;
$("#switch").click(function () {
if (toggle) {
$("#circle").css("left", "1px");
$("#white_rect").attr("src", "white_rect.png");
} else {
$("#circle").css("left", "27px");
$("#white_rect").attr("src", "green_rect.png");
}
toggle = !toggle;
});
});

It is better to strictly divide appearance and logic. So use .classes and backgounded <div>s instead of <img>. Then you won't need any state variables and code shall be more simple.
HTML:
<div class="container">
<div class="switch off"></div>
</div>
CSS:
.container {
width:100%; height:100px; padding:40px; text-align:center;
}
.container .switch {
width:94px; height: 27px; display:inline-block; background-color:pink; cursor:pointer;
}
.container .switch.on {
background: url('http://squad.pw/tmp/img/01-on.png') no-repeat 0 0;
}
.container .switch.off {
background: url('http://squad.pw/tmp/img/01-off.png') no-repeat 0 0;
}
JS:
$('.switch').click(function() {
// Do visual logic
$(this).toggleClass('on');
$(this).toggleClass('off');
// Do business logic
window.toggle = !window.toggle;
});
Here is FIDDLE

Related

Close menu on click outside - Vanilla JS

I created a side menu, which displays and hides when clicking the menu button. Now, I would like that the menu closes when I click outside the menu, but I cannot figure out how to do it.
I have tried adding a clicklistener to the body, but this disables the menu completely. I also thougt about getting the ID of the clicked element anywhere in the body and close the menu if clickedElement != sideBar && sideBar.style = "200px", but I cannot get it to work. Can someone help me out here? I would like to find a solution without JQuery.
menuBtn.addEventListener("click", function () {
if (sideBar.style.width == "200px") {
sideBar.style.width = "0px";
setTimeout(function () {
menuItems.style.display = "none";
}, 1000);
} else {
sideBar.style.width = "200px";
menuItems.style.display = "block";
}
});
You can add an event listener to the parent container and check if the click's target is inside the element or not, something like:
document.addEventListener("click", (e) => {
if (box.contains(e.target)) {
result.innerHTML = "inside";
} else {
result.innerHTML = "outside";
}
});
#box {
width: 100px;
height: 100px;
background-color: dodgerblue;
}
<div id="box"></div>
<div id="result"></div>

Why can I only change the css style once in javascript?

I want to be able to change the backgroundColor of a box between multiple colors using js but I cannot seem to find a way. Is it possible?
window.onload = function() {
var example=document.getElementById("example");
var click=0;
example.addEventListener("click", func);
function func(){
if (click===0){
example.style.backgroundColor=("red");
click=1;
}
if (click===1){
example.style.backgroundColor=("blue");}
click=0;
}
}
Your code checks to see if the value is zero. When it is, it sets it to one. Right after that if statement you see if it is one and set it back to zero.
You need to use else if or just else so it does not evaluate the next if statement.
function func(){
if (click === 0){
example.style.backgroundColor = "red";
click = 1;
}
//else if (click === 1) {
else {
example.style.backgroundColor = "blue";
click = 0;
}
}
Personally I would just toggle a class
var elem = document.querySelector("#test")
elem.addEventListener("click", function () {
elem.classList.toggle("on");
});
div.example {
background-color: blue;
}
div.example.on {
background-color: lime;
}
<div id="test" class="example">Click Me</div>

Javascript -- how to click anywhere on page to hide opened div

I have a javascript that opens up a hidden div:
<script>
function dropdown()
{ document.getElementById("login_dropdown").style.display="block"; }
</script>
The html is:
<div onclick="dropdown()">
<div id="login_dropdown">STUFF</div>
</div>
The CSS is:
<style>
#login_dropdown {
width: 150px;
display:none;
}</style>
Using javascript alone, how can I hide this div when I click anywhere else on the page, excluding the opened DIV itself.
Something like this with vanilljs
document.addEventListener('click', function(event){
const yourContainer = document.querySelector('....');
if(!yourContainer.contains(event.target)) {
//hide things classes.. yourContainer.classList.add('hidden');
}
});
You could do this
var elem = document.getElementById("login_dropdown");
(document.body || document.documentElement).addEventListener('click', function (event) {
// If the element on which the click event occurs is not the dropdown, then hide it
if (event.target !== elem)
elem.style.display="none";
}, false);
function closest(e, t){
return !e? false : e === t ? true : closest(e.parentNode, t);
}
container = document.getElementById("popup");
open = document.getElementById("open");
open.addEventListener("click", function(e) {
container.style.display = "block";
open.disabled = true;
e.stopPropagation();
});
document.body.addEventListener("click", function(e) {
if (!closest(e.target, container)) {
container.style.display = "none";
open.disabled = false;
}
});
#popup {
border: 1px solid #ccc;
padding: 5px;
display: none;
width: 200px;
}
<div id="container">
<button id="open">open</button>
<div id="popup">PopUp</div>
</div>
Something like this:
$("document").mouseup(function(e)
{
var subject = $("#login_dropdown");
if(e.target.id != subject.attr('id'))
{
subject.css('display', 'none');
}
});
works like this. When you click anywhere on the page, the handler fires and compares the ID of the open tab vs the id of the document (which there is none) - so it closes the tab. However, if you click the tab, the handler fires, checks the ID, sees the target is the same and fails the test (thus not closing the tab).

Click on button to toggle display of another div

I have a code that works perfectly to move elements from top, left, right or bottom sides, but seems to be, that it doesn't work with display property, here's my javascript code:
$('#icon-for-search').click(function () {
var targetValue;
if ($('#search-wrapper').css('top') == "0px") {
targetValue = '55px';
} else {
targetValue = '0px';
}
$("#search-wrapper").animate({
top: targetValue
}, 500);
});
I have a button with an id called "icon-for-search" and it toggles perfectly the top value of the #search-wrapper if it's clicked, but if I change it to display: block / none it doesn't work. Any particular reason? could someone explain me?
$('#icon-for-search').click(function () {
var targetValue;
if ($('#search-wrapper').css('display') == "none") {
targetValue = 'block';
} else {
targetValue = 'none';
}
$("#search-wrapper").animate({
display: targetValue
}, 500);
});
jQuery.animate works only with numeric CSS properties. You can just toggle element:
$('#icon-for-search').click(function () {
$('#search-wrapper').fadeToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="icon-for-search">Search Icon</div>
<div id="search-wrapper">Search Wrapper</div>

js/jquery form slides but not hiding in firefox

In my login page there are three forms,for Login,signup and pass reset.I wanted to show the login form only.and other two forms will appear if any user clicks the respective button.Every thing is doing fine in chrome.But in firefox the signup form always appears in the login page,but in the same time pass reset form is hiding there.My declaration of form properties are alright.I checked those.But I cant sort out the problem.
Here is the js code of hiding and slideup and fadein of forms :
$(document).ready(function () {
var login = $('#loginform');
var recover = $('#recoverform');
var speed = 400;
$('#to-recover').click(function () {
$("#loginform").slideUp();
$("#recoverform").fadeIn();
});
$('#to-login').click(function () {
$("#recoverform").hide();
$("#loginform").fadeIn();
});
$('#to-login').click(function () {
});
if ($.browser.msie == true && $.browser.version.slice(0, 3) < 10) {
$('input[placeholder]').each(function () {
var input = $(this);
$(input).val(input.attr('placeholder'));
$(input).focus(function () {
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
$(input).blur(function () {
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.val(input.attr('placeholder'));
}
});
});
}
});
and here is the css part
#loginbox form#loginform { z-index: 200; display:block;}
#loginbox form#recoverform { z-index: 100; display:none;}
#loginbox form#recoverform .form-actions { margin-top: 10px;}
#loginbox form#signupform { z-index: 150; display:none;}
#loginbox form#signupform .form-actions { margin-top: 10px;}
Can somebody please let me know where I am doing wrong.I think I did something wrong in css part,but chrome is showing perfectly thats why I am wondering.

Categories