Controlling multiple CSS events with single Function - javascript

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>

Related

How do I loop through HTML elements while executing a function on each element

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>

horizontal scrolling jquery working on entire page

I am working on a site.I need horizontal scrolling on a particular section,for that i am using JinvertScroll jquery.When i run that jquery's example the scrolling is working on entire page.how can i set the scrolling for particular section only??I mean how can i set that particular div that should scroll?Here is the code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/example.css" />
</head>
<body>
<section id="scrolll">
<div class="middle scroll" style="border:solid red;backgroun:red">
<img src="images/middle.png" alt="" />
</div>
<script type="text/javascript" src="../libs/jquery.min.js"></script>
<script type="text/javascript" src="../src/jquery.jInvertScroll.js"></script>
<script type="text/javascript">
(function($) {
var scrolll= document.getElementById('scrolll');
var elem = $.jInvertScroll(['.scroll'], // an array containing the selector(s) for the elements you want to animate
{
height: 600, // optional: define the height the user can scroll, otherwise the overall length will be taken as scrollable height
onScroll: function(percent) { //optional: callback function that will be called when the user scrolls down, useful for animating other things on the page
console.log(percent-50);
}
});
$(window).resize(function() {
if ($(window).width() <= 768) {
elem.destroy();
}
else {
elem.reinitialize();
}
});
}(jQuery));
</script>
</section>
<section>
<div style="border:solid orange;height:1000px"></div>
</section>
</body>
</html>
<div id="scrollDiv" style="overflow:auto;">
// write code here over which scroll will be applied
</div>
The section you want to scroll place it inside a div . Give that div an Id e.g. scrollDiv and Place a style attribute on it as shown in the example above.
You don't need plugin for that. Just use height and overflow-y where you want a scroll
#scrolll{height: 600px;
overflow-y: scroll;}
<section id="scrolll">
<div class="middle scroll" style="border:solid red;backgroun:red">
<img src="images/middle.png" alt="" />
</div>
</section>
<section>
<div style="border:solid orange;height:1000px"></div>
</section>

How to convert all inline style css with dynamic class with jQuery?

I am trying to capture all inline css and append it to style tag with unique class name.
i.e. from
<div style="top: 250px; left: 250px;" class="search">
to
<div class="search custom-class1">
Where custom-class will be created dynamically in css style tag.
Is there any way of doing this with jQuery?
Any help would be appreciated.
<div id="a" class="a" style=".."></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
..
var inlineStyle = $('#a').attr('style');
$('.a').attr('style', inlineStyle);
if i undertand the task, the solution will be this
Although there would be many other ways to handle your situation. But If you really want to do like this. try this code, however its working but if you want any enhance you can easily go further.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<html>
<head>
<title>test</title>
</head>
<body>
<div style="color:black;">
<div style="color:blue;">abc</div>
<div>Xyz</div>
1111
</div>
</body>
</html>
<script type="text/javascript">
allstyle = "";
classNames = "";
count = 1;
$("*").each(function() {
tag = $(this);
$.each(this.attributes, function() {
if(this.name == 'style'){
allstyle += this.value;
tag.removeAttr("style");
tag.addClass("custom-class"+count);
classNames +=" .custom-class"+count+"{"+allstyle+"}";
count++;
}
});
});
$("<style>").html(classNames).appendTo("head");
</script>

How to make the last div receive y overflow?

Let's say my html is setup like this:
<html>
<head>
</head>
<body>
<div id="site_banner">
<img>
</div>
<div id="site_content">
<div id="home_menu"></div>
<div id="home_content"></div>
</div>
</body>
</html>
All I want is my home_content to fill the rest of the view and then any additional content in home_content to be in overflow instead of overflow being in html, so that the site_banner and home_menu are always on screen as the user scrolls down and never disappears.
From what you're saying it sounds like you should be putting the "site banner" and "home menu" in a header tag which means it should be structured like this.
<html>
<head>
</head>
<body>
<header>
<div id="site_banner"><img></div>
<div id="home_menu"></div>
</header>
<div id="site_content">
<div id="home_content"></div>
</div>
</body>
here's a fiddle of it https://jsfiddle.net/Optiq/rx2qn1h9/
Here's the CSS I added to make it stay put
header{
position:fixed; /*this makes it stay in place*/
display:block;
top:0px; /*this bumps it to the very top of the page*/
width:100%;
height:80px;
background-color:red;
}
Using jQuery:
$("#site_content").height($(window).height()-$("#site_banner").height());
$("#home_content").css("overflow-y","auto").height($("#site_content").height()-$("#home_menu").height());
Here's a JSfiddle:
http://jsfiddle.net/h1bcn5p0/

Find a class using js and localStorage

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>

Categories

Resources