I'm trying to convert a value stored by localStorage and then turn it into a class so I can manipulate it in the DOM.
I'm very new to javascript, so please allow me to explain:
I have a html file with multiple divs, and localStorage stores the class of the div that was last clicked.
I want my script to call the stored class from localStorage, find the div with that class (using jquery OR js, doesn't matter) and then change the background colour of that div using .css(), for example. I'll be able to do what I need to do with that logic, but I can't get it to work.
So what I am trying to do is $('the last clicked div').css({..manipulate the css..});
Is this possible?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<script type="text/javascript">
$(document).ready(function () {
//always show the current div class
$("b").html(localStorage.getItem("currentDiv"));
//get the class of the div that's just been clicked
$("div").click(function(){
var currentClass = $(this).attr("class");
localStorage.setItem("currentDiv", currentClass);
$("b").html(localStorage.getItem("currentDiv"));
});
//show the div that was last clicked
function currentStatus(){
if (localStorage.getItem("currentDiv") === $(currentClass))
{
$(currentClass).show();
$("b").html(localStorage.getItem("currentDiv"));
}
}
//set a color for the recently clicked div dynamically, not by .click
var highlightClass = localStorage.getItem("currentDiv");
highlightClass.css({
'background' : 'black'
})
});
$('#localStorageTest').submit(function() {
localStorage.clear();
});
</script>
<style type="text/css">
[class*="slide"]{
display: inline-block;
padding: 40px;
background: #999;
margin: 20px;
}
/*.slide1{
display: block;
}*/
</style>
</head>
<body onLoad="currentStatus()">
<div class="slide1">
<h1>"A question would go here."</h1>
</div>
<div class="slide2">
<h1>"A question would go here."</h1>
</div>
<div class="slide3">
<h1>"A question would go here."</h1>
</div>
<div class="slide4">
<h1>"A question would go here."</h1>
</div>
<div class="slide5">
<h1>"A question would go here."</h1>
</div>
<div class="slide6">
<h1>"A question would go here."</h1>
</div>
<div class="slide7">
<h1>"A question would go here."</h1>
</div>
<b></b>
</body>
</html>
Here's how to make it work, the core thing being: $("."+currentDivClass) which converts the string to a class!
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style type="text/css">
[class*="slide"]{
display: inline-block;
padding: 40px;
background: #999;
margin: 20px;
}
/*.slide1{
display: block;
}*/
</style>
</head>
<body>
<div class="slide1">
<h1>"1 A question would go here."</h1>
</div>
<div class="slide2">
<h1>"2 A question would go here."</h1>
</div>
<div class="slide3">
<h1>"3 A question would go here."</h1>
</div>
<div class="slide4">
<h1>"4 A question would go here."</h1>
</div>
<div class="slide5">
<h1>"5 A question would go here."</h1>
</div>
<div class="slide6">
<h1>"6 A question would go here."</h1>
</div>
<div class="slide7">
<h1>"7 A question would go here."</h1>
</div>
<b></b>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//always show the current div class
$("b").html(localStorage.getItem("currentDiv"));
//get the class of the div that's just been clicked
$("div").click(function(){
var currentClass = $(this).attr("class");
localStorage.setItem("currentDiv", currentClass);
$("b").html(localStorage.getItem("currentDiv"));
});
//convert the string of the last clicked div into a class and then work your magic
var currentDivClass = localStorage.getItem("currentDiv");
$("."+currentDivClass).css({
'background' : 'red'
});
});
$('#localStorageTest').submit(function() {
localStorage.clear();
});
</script>
</body>
</html>
Related
I have a hidden class fadeThis, which does not appear when I hover over the button.
Perhaps it is clashing with another class/div?
What I'm essentially trying to do is create a red fade in over the grey box, when the cursor hovers over the button, and then when the cursor leaves the box(not the button), I want it to return back to it's original state.
I've also added the CSS to help demonstrate
HTML
<div class="imageOne">
<div class="onClickThis"> <!-- hidden by default-->
<h2 class="fadeThis">Whatever the text needs to be</h2> <!-- hidden by default-->
</div>
<div class="centerButton">
<button class="btn">View More</button>
</div>
</div>
CSS
.imageOne{
height: 300px;
width: 400px;
background-color: grey;
}
.centerButton{
display: flex;
justify-content:center;
padding-top:150px;
}
.btn{
height: 30px;
width:170px;
}
.onClickThis{
height: 300px;
width: 400px;
background-color: tomato;
}
JavaScript
$(document).ready(function () {
$(".onClickThis").hide();
$(".fadeThis").hide();
$(".btn").hover(function () {
$(".imageOne").fadeIn("slow", function () {
$(this).addClass("fadeThis onClickThis");
$(".btn").remove();
});
$(".onClickThis").mouseleave(function () {
$(this).removeClass("fadeThis onClickThis");
});
});
});
I don't understand exactly what you are looking for. Maybe you could provide more details.
Here is a demo started from your code with some changes added.
$(document).ready(function () {
$(".onClickThis, .fadeThis").hide();
$(".btn").hover(function () {
$(".imageOne").fadeIn("slow", function () {
$(".onClickThis, .fadeThis").fadeIn( 250 );
$(".btn").fadeOut();
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="imageOne">
<div class="onClickThis"> <!-- hidden by default-->
<h2 class="fadeThis">Whatever the text needs to be</h2> <!-- hidden by default-->
</div>
<div class="centerButton">
<button class="btn">View More</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
I am a newbie to Javascript, I wanted to implement a for loop that would go through each div as selected by its class.
The simple idea is to reveal DIVs when I click on a button. But it has to be sequential: I click DIV1 appears, when I click again DIV2 appears and so on. Currently my code only changes the class of one DIV and not the rest. Here are my code samples:
$(document).ready(function(){
// jQuery methods go here...
var count = document.getElementById("page1").childElementCount;
for(var i = 0; i < count; i++){
var myClass = ".panel" + i;
$("button").click(function(){
$(myClass).addClass("showing animated fadeIn")
});
}
});/**document ready **/
.showing{
background-color: red;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<link rel="stylesheet" type="text/css" href="animate.css">
</head>
<body>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1">
</div>
<div class="panel2">
</div>
<div class="panel3">
</div>
<div class="panel4">
</div>
</div><!-- page one -->
<div id="trial">
</div>
<script src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="jquery.touchSwipe.min.js"></script>
<script type="text/javascript" src="trial.js"></script>
</body>
</html>
Please let me know what I am missing especially in the for loop or if I can do something else to be able to grab a DIV and add a class every time I click on the button.
Firstly, the HTML attribute class is made for multiple elements with the same style/behaviour. You should use id if it is to dissociate one panel for another.
You have to store a count variable to know which panel has to appear next.
And always try to do what you want in Javascript without jQuery if it is possible !
var i = 1;
function clickBtn() {
if (!document.getElementById("panel-" + i))
return;
document.getElementById("panel-" + i).classList.add("visible");
i++;
}
.panel {
width: 50px;
height: 50px;
display: none;
margin: 5px;
background-color: #bbb;
}
.panel.visible {
display: block;
}
<button onclick="clickBtn()">click me</button>
<div>
<div id="panel-1" class="panel"></div>
<div id="panel-2" class="panel"></div>
<div id="panel-3" class="panel"></div>
<div id="panel-4" class="panel"></div>
</div>
You could use counter like clickCount instead of for loop
$(document).ready(function(){
// jQuery methods go here...
var clickCount = 1;
$("button").click(function(){
var myClass = ".panel" + clickCount;
$(myClass).addClass("showing animated fadeIn")
clickCount++;
});
});/**document ready **/
.showing{
background-color: red;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<link rel="stylesheet" type="text/css" href="animate.css">
</head>
<body>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1">
</div>
<div class="panel2">
</div>
<div class="panel3">
</div>
<div class="panel4">
</div>
</div><!-- page one -->
<div id="trial">
</div>
<script src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="jquery.touchSwipe.min.js"></script>
<script type="text/javascript" src="trial.js"></script>
</body>
</html>
You've got this a little bit backwards; you're trying to attach an event handler to the button for each element. Instead, you should have one event handler for the button, which cycles through the elements.
You could set a variable to keep track of which element is currently highlit, but it's easier to just determine that based on the current state of the DOM:
$(document).ready(function() {
$('button.one').click(function() {
$('.showing') // find the current element
.removeClass('showing') // clear it
.next() // find its next sibling
.addClass('showing'); // show that
if ($('.showing').length === 0) {
// nothing is showing, so show the first one
$('#page1 div:eq(0)').addClass('showing')
}
})
})
#page1 div {height: 10px}
#page1 div.showing {background-color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1"></div>
<div class="panel2"></div>
<div class="panel3"></div>
<div class="panel4"> </div>
</div>
There's a small cheat in the above -- if the current element is the last one, then it won't have a next() to highlight. That's why I waited to check for the case where there's nothing visible until after moving the highlight; that way it will work for both the first click, and for when you need the highlight to loop back around to the first element.
If you intended to have the elements reveal themselves in sequence and not hide earlier ones, just get rid of the .removeClass('showing') line:
$(document).ready(function() {
$('button.one').click(function() {
$('.showing') // find the current element
.next() // find its next sibling
.addClass('showing'); // show that
if ($('.showing').length === 0) {
// nothing is showing, so show the first one
$('#page1 div:eq(0)').addClass('showing')
}
})
})
#page1 div {height: 10px}
#page1 div.showing {background-color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1"></div>
<div class="panel2"></div>
<div class="panel3"></div>
<div class="panel4"> </div>
</div>
What you can do is count the amount of children that you have, and compare the amount of clicks through a given iterator you have to see what should be shown.
I added an extra functionality that hides the elements again once the max amount of divs has been shown.
Hope this helps.
$(document).ready(function() {
$('#page1').children().each(function () {
$(this).hide();
});
});
var panel="panel";
var pannelNum=0;
var count = $("#page1").children().length;
$(".one").on( "click", function() {
pannelNum=pannelNum+1;
if(pannelNum > count) {
$('#page1').children().each(function () {
$(this).hide();
});
pannelNum=0;
}
else {
clicked=panel+""+pannelNum;
$('.'+clicked).show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1">
this is panel 1!
</div>
<div class="panel2">
this is panel 2!
</div>
<div class="panel3">
this is panel 3!
</div>
<div class="panel4">
this is panel 4!
</div>
</div><!-- page one -->
<div id="trial">
</div>
I have this html structure:
<section>
<div class="v-middle">
<div class="row">
<h5 class="heading">Heading goes here</h5>
</div>
</div>
</section>
And I need to add the class "newClass" to the parent Section tag when the h5 has .heading class.
I tried the following but it didn't work and I don't know why:
$('.heading').parent('section').addClass('newClass');
DEMO
https://fiddle.jshell.net/4smhxoL6/1/
.parent looks at the immediate parent, which isn't a section, but a div. You want closest:
$('.heading').closest('section').addClass('newClass');
https://fiddle.jshell.net/4smhxoL6/2/
you could use closest() instead of parent() .parent matching immediate parent. closest matching the parent first section detect
$('.heading').closest('section').addClass('newClass');
section {
width:100%;
height: 200px;
}
.newClass {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div class="v-middle">
<div class="row">
<h5 class="heading">Heading goes here</h5>
</div>
</div>
</section>
Change parent to parents.
$('.heading').parents('section').addClass('newClass');
or
You can use
$('.heading').closest('section').addClass('newClass');
working fiddle: https://fiddle.jshell.net/1y3ejtjz/
Instead of parent method,try parentsUntil method.For details,see jQuery Traversing - Ancestors
$('.heading').parentsUntil('section').addClass('newClass');
Demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
section {
width: 100%;
height: 200px;
}
.newClass {
background: red;
}
</style>
</head>
<body>
<section>
<div class="v-middle">
<div class="row">
<h5 class="heading">Heading goes here</h5>
</div>
</div>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$('.heading').parentsUntil('section').addClass('newClass');
</script>
</body>
</html>
Hope it could help you.
All of the posted answers are forgetting 1 thing:
And I need to add the class "newClass" to the parent Section tag when
the h5 has .heading class.
newClass should only be applied when the <h5> element has heading class.
This code should do the trick.
var heading = $('.heading');
if (heading.length && heading.is('h5')) {
heading.closest('section').addClass('newClass');
}
https://jsfiddle.net/4yo72hhd/
You can use below code for specific h5 with .heading class. Because if this heading class available in other element this will protect you.
$('h5.heading').closest('section').addClass('newClass')
I am struggling to change CSS based on user actions with some script. Currently I have each navBar button performing 5 functions onClick. 1 each to change the CSS of 5 different divs. Since I am newer to scripting, I wanted to make an example similar to what I am doing in order to refer back in the future as well as hopefully help out the next person to come along.
Can someone please help me with this short example? I have tried many various scripts and just end up destroying my spirits.
For this, I want to click an openButton in the navBar and have it change the width (essentially open) a corresponding div on the page.
<div id="navBar">
<a id="div1OpenButton" class="openButton" onClick="openDiv()">div1</a>
<a id="div2OpenButton" class="openButton" onClick="openDiv()">div2</a>
<a id="div3OpenButton" class="openButton" onClick="openDiv()">div3</a>
</div>
<div id="main">
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
</div>
<style>
#div1 {width: 0px;}
#div2 {width: 0px;}
#div3 {width: 0px;}
</style>
Don's use onclick within your HTML - that is bad practice. You want a separation of concerns, with your JS in a separate file.
If you use jQuery (which a good library for a use-case like this), you can use its powerful selector to select all five elements at the same time. jQuery's selector is nice for beginners because it's identical to how you use selectors in CSS.
I also like to attach my JS to my HTML via IDs, not classes. This way, you know your JS has unique HTML targets to attach to.
Putting all of this together, use the jQuery selector to select all buttons, then use a .click() event to encapsulate your CSS manipulation in an anonymous function:
$(".openButton").click(function() {
$("#div1, #div2, #div3").css("width", "500px");
});
There are better ways to do it, but following the line of your code, you must pass a param to your openDiv function such as the ID of the element you want to show.
<a id="div1OpenButton" class="openButton" onClick="openDiv('div1')">div1</a>
Your onClick function must to hide all divs inside your "main" and show only the id you just passed by param.
If you need more help, paste your code please.
Try this
<html><head>
<script src=path/to/jquery.js></script>
</head><body>
<div id="navBar">
<!-- openDiv(1) with "1" is the div number -->
<a id="div1OpenButton" class="openButton" onClick="openDiv(1)">div1</a>
<a id="div2OpenButton" class="openButton" onClick="openDiv(2)">div2</a>
<a id="div3OpenButton" class="openButton" onClick="openDiv(3)">div3</a>
</div>
<div id="main">
<div id="div1">div1 opened</div>
<div id="div2">div2 opened</div>
<div id="div3">div3 opened</div>
</div>
<style>
div#main div {overflow:hidden;width:0px} //to hide div content while closed
</style>
<script>
function openDiv(n) {
$('#div'+n).width(400);} // set width to 400px
</script>
</body></html>
OR without the inline onClick()
<html><head>
<script src=path/to/jquery.js></script>
</head><body>
<div id="navBar">
<a id="div1" class="openButton" >div1</a>
<a id="div2" class="openButton" >div2</a>
<a id="div3" class="openButton" >div3</a>
</div>
<div id="main">
<div id="div1">div1 opened</div>
<div id="div2">div2 opened</div>
<div id="div3">div3 opened</div>
</div>
<style>
div#main div {overflow:hidden;width:0px} //to hide div content while closed
</style>
<script>
$('a.openButton').click(function() {
var itm = $(this).attr("id");
$("#main div#"+itm).width(400);} );// set width to 400px
</script>
</body></html>
Firstly, don't mix HTML, CSS and JavaScript in the same file. You should write your JavaScript code in a .js file, and your styles in an external stylesheet ;
Add handlers on events in your JavaScript code by using element.addEventListener() ;
Use data attributes on your buttons to link them with target divs.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>My page</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id="navBar">
<a class="openButton" data-target="div1">div1</a>
<a class="openButton" data-target="div2">div2</a>
<a class="openButton" data-target="div3">div3</a>
</div>
<div id="main">
<div id="div1" class="container hide"></div>
<div id="div2" class="container hide"></div>
<div id="div3" class="container hide"></div>
</div>
</body>
</html>
And in the script.js file:
document.addEventListener('DOMContentLoaded', function(event) {
var divs = document.querySelectorAll('.openButton');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', openDiv);
}
});
function openDiv(e) {
// Use e.target.dataset.target
// Add 'hide' class on all containers
var containers = document.querySelectorAll('.container');
for (var i = 0; i < containers.length; i++) {
containers[i].classList.add('hide');
}
// Remove 'hide' class on the container to display
document.getElementById(e.target.dataset.target).classList.remove('hide');
}
<a id="div1OpenButton" class="openButton" onClick="openDiv(this)">div1</a>
<script>
function openDiv(e){
document.getElementById(e.innerHTML).style.width= '20px'
}
</script>
This is inside my CSS:
div.hide {
display:none;
}
div.show {
color: #66CCFF;
}
This is in my HTML:
16:10
<script language="JavaScript">
function showText(show,hide)
{
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<a name="16:10" onclick="showText('text1')" href="javascript:void(0);"></a>
<div id="text1" class="hide">This is your monitors aspect ratio.</div>
I'm trying to make the first link display the "This is your monitors aspect ratio." text lower on the page.
Any help is much appreciated.
Pure CSS Answer
Ok, if you just want to append text after you have moved to a position in a page using an anchor tag, you could do it with nothing but CSS similar to the following:
a:target:after{
content: " Test";
background-color: #ccffcc;
}
What this does is appends the text "Test" after the active anchor and colors. Here is an example page with implementation:
<!DOCTYPE html>
<html>
<head>
<title>Link Printer 2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
a:target:after{
content: " Test";
background-color: #ccffcc;
}
.bigSection{
height: 200px;
}
</style>
</head>
<body>
<div class="bigSection">
<div><a name="first">First</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
<div class="bigSection">
<div><a name="second">Second</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
<div class="bigSection">
<div><a name="third">Third</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
</body>
</html>
Answer using JavaScript
You need to bind an eventListener and prevent it from moving to the next page. Here is a way to do it with JavaScript or CSS. The JavaScript way will actually set the text to whatever you want. The CSS way will hide actually hide the element.
<!DOCTYPE html>
<html>
<head>
<title>Link Printer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
.hide{
display: none;
}
</style>
<script>
function jsShowText(event) {
var divToManip = document.getElementById("text");
if (divToManip.innerHTML === "") {
divToManip.innerHTML = "Hello";
}
else {
divToManip.innerHTML = "";
}
event.preventDefault();
}
function cssShowText(event) {
var divToManip = document.getElementById("text");
if (divToManip.className === "") {
divToManip.className = "hide";
}
else {
divToManip.className = "";
}
event.preventDefault();
}
function setListeners() {
document.getElementById("jsPrinter").addEventListener("click", jsShowText, false);
document.getElementById("cssPrinter").addEventListener("click", cssShowText, false);
}
window.onload = setListeners;
</script>
</head>
<body>
<div><a id="jsPrinter" href="" onclick="showText();">Click With JavaScript</a></div>
<div><a id="cssPrinter" href="" onclick="showText();">Click With CSS</a></div>
<div id="text">I'm text</div>
</body>
</html>
"showText" must receive an id parameter to be used with the call to "document.getElementById"
Try this, just 1 link that will display the text below after click:
<a name="16:10" onclick="showText('text1')" href="javascript:void(0);">16:10</a>
<script language="JavaScript">
function showText(id)
{
document.getElementById(id).style.display = "block";
}
</script>
<div id="text1" style="display:none;">This is your monitors aspect ratio.</div>
I'm just using style display to hide/show the element. Hope it helps.
just change your css like this:
div.show {
display:block;
color: #66CCFF;
}
Here I am going to provide an example with something that I was working, thank you Alberto Montellano for the example, that gave me an idea, however what was required at the end was something a little different, with the option not to show the data and display it only when I click and make it disappear when click again. In this example I am going to give you two options; you can have a button or a link to trigger the JS function to display and hide the body text, you can choose if you want the button or link that is way I put a comment (optional), both behave as the same, it is up to you which one you want to use.
<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top:20px;
}
</style>
</head>
<body>
<!-- text before the button or link -->
<p>Click the "PIN" button (or link) to display PIN options:</p>
<!-- The Pin button (optional) -->
<button type="button" onclick="myFunction()">PIN button:</button>
<!-- The Pin link (optional) -->
</br></br></br>
<a onclick="myFunction()" href="javascript:void(0);">PIN link:</a>
<!--Data will display or hide (toggle)-->
<div id="myDIV"style="display:none;">
These are the steps to get your PIN number: Bla bla bla.
</div>
<p><b>Note:</b> The text display when you click the button or link will take space, if you click again will be toggle.</p>
<!-- JS -->
<script>
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
</body>
</html>