Saving a toggled class Div (with local storage) - javascript

So I have an example of a basic classtoggle with a div but can I make it so the "active class" can stay switched with a refresh/re-open. Could this be done?
function myfunc(div) {
var className = div.getAttribute("class");
if(className=="normal") {
div.className = "active";
}
else{
div.className = "normal";
}
}
.normal /*Default*/
{width:25%; height:25%; background: #ffeb00;}
.active /*Switch*/
{width:25%; height:25%; background: #ff00e2;}
<html>
<head>
<title>Test</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>
<div id="div" class="normal" onclick="myfunc(this)"></div>
<script src=".jquery-3.2.1.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Thank You for all future Answers.

Use the localStorage to hold the last class
try jsfiddle
$("#div").addClass(localStorage.getItem('ClassName')) ;
$("#div").on("click",function(){
if($(this).hasClass('active')){
$(this).removeClass("active").addClass("normal");
localStorage.setItem('ClassName', 'normal');
}
else{
$(this).removeClass("normal").addClass("active");
localStorage.setItem('ClassName', 'active');
}
});

Something similar to this, haven't tested but this will get you on the right track (note that snippet cannot run on stack overflow due to being sandboxed)
function localStorageExists() {
if (typeof(Storage) !== "undefined") {
return true;
}
return false;
}
if (localStorageExists()) {
myfunc(document.getElementById('div'));
}
function myfunc(div) {
var className = div.getAttribute("class");
if (className == "normal" || (localStorageExists() && localStorage.getItem('someKey') == 'active')) {
div.className = "active";
localStorage.setItem('someKey', 'active');
} else if (className == "active" || (localStorageExists() && localStorage.getItem('someKey') == 'normal')) {
div.className = "normal";
localStorage.setItem('someKey', 'normal');
}
}
.normal
/*Default*/
{
width: 25%;
height: 25%;
background: #ffeb00;
}
.active
/*Switch*/
{
width: 25%;
height: 25%;
background: #ff00e2;
}
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="div" class="normal" onclick="myfunc(this)"></div>
<script src=".jquery-3.2.1.min.js"></script>
<script src="script.js"></script>
</body>
</html>

Related

Hide div class when click outside

function nav_category_show() {
var x = document.getElementById("nav_dropdown_items");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
}
else {
x.className = x.className.replace(" w3-show", "");
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<span onclick="nav_category_show()">click here<i class="fa fa-bars"></i></span>
<div id="nav_dropdown_items" class="w3-animate-zoom w3-dropdown-content w3-bar-block w3-card-4">
Link 1
</div>
I want to hide this #nav_dropdown_items when click on outside of the div.How should I do it? Thank you!
After adding class in the nav_category_show function stop the event propagation using event.stopPropagation.
Add another event to the body and in that remove the class from nav_category_show
function nav_category_show(e) {
var x = document.getElementById("nav_dropdown_items");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
} else {
x.className = x.className.replace("w3-show", "");
}
e.stopPropagation();
}
document.body.addEventListener('click', function() {
document.getElementById("nav_dropdown_items").classList.remove('w3-show');
})
body {
width: 500px;
height: 500px;
border: 1px solid red;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<span onclick="nav_category_show(event)">click here<i class="fa fa-bars"></i></span>
<div id="nav_dropdown_items" class="w3-animate-zoom w3-dropdown-content w3-bar-block w3-card-4">
Link 1
</div>
Since you're already referencing jquery, you can use it to easily hide / show the div of choice:
var target = $("#nav_dropdown_items");
if(target.hasClass("w3-show")) {
target.hide(); // hides it
target.removeClass("w3-show");
}
else {
target.show(); //shows it
target.addClass("w3-show");
}

how to give draggable element into specific location

I am trying to move my JQuery UIdraggable container into div(id="frame") but it is dragging everywhere in the webpage. So how can I move my draggable container into specific div(id="frame").So please give me a way to solve this problem. I am trying to make my own custom product designer plugin for which this my first feature.Here is my code :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dragg</title>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css"/>
<style>
#draggable {
overflow:hidden;
width: 100px;
height: 100px;
padding: 0.5em;
background-color: transparent;
}
#frame {
overflow:hidden;
width: 350px;
height: 500px;
padding: 0.5em;
border : 1px solid black;
}
</style>
</head>
<body>
<input type = "file" id="inputFileToLoadOuter">
<input type = "button" onclick = "loadImageFileAsURL(1)" value = "LoadOuterImage">
<input type = "file" id="inputFileToLoadInner">
<input type = "button" onclick = "loadImageFileAsURL(2)" value = "LoadInnerImage">
<div id="frame">
<img src="" id="OuterImg" style="width: 100% ; height:100%" />
</div>
<div id="draggable">
<img src="" id="InnerImg" style="width: 100% ; height:100%" />
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#draggable" ).resizable().draggable();
} );
function loadImageFileAsURL(pos)
{
if(pos == 1){
var filesSelected = document.getElementById("inputFileToLoadOuter").files;
}else{
var filesSelected = document.getElementById("inputFileToLoadInner").files;
}
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
if(pos == 1){
var imageLoaded = document.getElementById("OuterImg");
}else{
var imageLoaded = document.getElementById("InnerImg");
}
imageLoaded.src = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(fileToLoad);
}
}
}
</script>
</body>
</html>
plunker : https://plnkr.co/OubL3Uw0G7gi4d01yx0V
Modify your #draggable object to this
$("#draggable").resizable().draggable({
revert: "invalid",
});
and add this to make you #frame droppable
$('#frame').droppable({
accept: '#draggable',
})
Read up the jqueryui docs on this, there is much more you can achieve with this. See here https://jqueryui.com/droppable/#photo-manager
You need to use accept of droppable. Like this
$('#frame').droppable({
accept: '#draggable',
})
It will solve you problem :)
For more knowledge visit
JQuery UI

If statement in a for loop being ignored

I have a for loop which has an if statement nested inside of it, but the loop is ignoring the statement and continuing to run. Any ideas why this could be? Many thanks.
JavaScript:
var sheet = document.styleSheets[0];
var cssVal = '';
function changeColor() {
for (i = 0; i < sheet.cssRules.length; i++) {
cssVal = sheet.cssRules[i];
console.log(cssVal); // Successfully outputs #box to the console.
if (cssVal == "#box") { // Does nothing, continues iterating.
console.log("If has run.");
cssVal.style.backgroundColor="blue";
break;
}
}
}
changeColor();
CSS:
#charset "utf-8";
#box {
width:20px;
height:20px;
}
#car {
width:20px;
height:20px;
}
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Boxes</title>
<link href="Boxes.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="box"></div>
<div id="car"></div>
<script type="text/javascript" src="Boxes.js"></script>
</body>
</html>
Obviously it isn't going inside the if, that's because cssVal is not a string, it's a CSSStyleRule object. You should do this instead:
cssVal = sheet.cssRules[i];
Then in your if:
if (cssVal.selectorText == '#box')
And then, to change the color:
cssVal.style.backgroundColor = "blue";

Need to Toggle DIV Visibility for 2 DIVs

I need show a DIV full of dimensions and weights in English measure, and have a link allowing the user to toggle to a hidden DIV that instead displays Metric. Trying the markup below, but it's not working. It refuses to toggle. I've tested with the first div given no style and with its style'"display: block;" and neither works. What am I missing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
<!--
body {
color:#000000;
background-color:#FFFFFF;
}
a { color:#0000FF; }
a:visited { color:#800080; }
a:hover { color:#008000; }
a:active { color:#FF0000; }
-->
</style>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript">
function toggle_visibility(eng, met) {
var e1 = document.getElementById(eng);
var e2 = document.getElementById(met);
if(e1.style.display == 'block')
e1.style.display = 'none';
e2.style.display = 'block';
else
e1.style.display = 'block';
e2.style.display = 'none';
}
</script>
</head>
<body>
<div id="eng" style="display: block;">
This is English<br />
Convert to Metric
</div>
<div id="met" style="display: none;">
This is Metric<br />
Convert to English
</div>
</body>
</html>
Try this if-statement:
if(e1.style.display == 'block') {
e1.style.display = 'none';
e2.style.display = 'block';
} else {
e1.style.display = 'block';
e2.style.display = 'none';
}
Got it working. I thought I'd post the solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
<!--
body {
color:#000000;
background-color:#FFFFFF;
}
a { color:#0000FF; }
a:visited { color:#800080; }
a:hover { color:#008000; }
a:active { color:#FF0000; }
-->
</style>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript">
function toggle_visibility() {
var e1 = document.getElementById("eng");
var e2 = document.getElementById("met");
if(e1.style.display == 'block') {
e1.style.display = 'none';
e2.style.display = 'block';
}
else {
e1.style.display = 'block';
e2.style.display = 'none';
}
}
</script>
</head>
<body>
<div id="eng" style="display: block;">
This is English<br />
Convert to Metric
</div>
<div id="met" style="display: none;">
This is Metric<br />
Convert to English
</div>
</body>
</html>

error in javascript toggle class

I have this code for toggling class using pure JavaScript that I found online and it is not working when I am using it in an offline website
my code is -
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
any help would be appreciated
Move the script below the div you are looking for in the source code.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
</body>
</html>
You cannot manipulate the dom before it is ready.
So either load the script that adds the handler at the end of the body tag, or use the DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
Try adding the event handler after the div has rendered - for example in the onload event
Live Demo
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
if (!this.classList) return; // no support
this.classList.toggle('class1');
this.classList.toggle('class2');
}
window.onload=function() {
document.getElementById('div').onclick=classToggle;
}
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
codepen demo
//vanilla js -- toggle active class
// el = object containing the elements to toggle active class and the parent element
var el = {
one: document.getElementById('one'),
two: document.getElementById('two'),
three: document.getElementById('three'),
hold: document.getElementById('hold')
};
// func = object containing the logic
var func = {
toggleActive: function(ele) {
ele = event.target;
var hold = el.hold.children;
var huh = el.hold.children.length;
var hasActive = ele.classList.contains('active');
for (i = 0; i < huh; i++) {
if (hold[i].classList.contains('active')) {
hold[i].classList.remove('active');
}
}
if (!hasActive) {
ele.classList.add('active');
}
}
};
//add listeners when the window loads
window.onload = function() {
var holdLen = el.hold.children.length;
for (i = 0; i < holdLen; i++) {
el.hold.children[i].addEventListener("click", func.toggleActive);
}
};

Categories

Resources