Toggle div using javascript - javascript

I'm trying to use this jsfiddle but it's not working offline. Can you please point out the error: http://jsfiddle.net/2ofkr7ph/
This is my code but it's not working on local.
<html>
<head>
<title>BUILD</title>
<style>
.menu > li {
display:inline-block;
font-weight:bold;
padding:6px 10px;
cursor:pointer;
border:2px solid tomato;
margin:5px;
}
.container {
border:2px solid black;
margin:5px;
}
.container > div {
display:none;
}
.container > div:first-child {
display:block;
}
</style>
<script>
var menu_elements = document.querySelectorAll('.menu>li'),
menu_length = menu_elements.length;
for (var i = 0; i < menu_length; i++) {
menu_elements[i].addEventListener('click', function (e) {
var target = document.querySelector('.container>.' + e.target.classList[0]); // clicked element
Array.prototype.filter.call(target.parentNode.children, function (siblings) {
siblings.style.display = 'none'; // hide sibling elements
});
target.style.display = 'block'; // show clicked element
});
}
</script>
</head>
<body>
<ul class="menu">
<li class="toggle1">One</li>
<li class="toggle2">Two</li>
<li class="toggle3">Three</li>
<li class="toggle4">Four</li>
<li class="toggle5">Five</li>
</ul>
<div class="container">
<div class="toggle1">Here are the contents of 1.</div>
<div class="toggle2">Here are the contents of 2..</div>
<div class="toggle3">Here are the contents of 3...</div>
<div class="toggle4">Here are the contents of 4....</div>
<div class="toggle5">Here are the contents of 5.....</div>
</div>
</body>
</html>
It's working fine on JSFiddle website, but not working on local machine.

The script is loaded and executed BEFORE the HTML elements are encountered. You can move the script to below the BODY tag and it works offline.
Good Luck!

Just add the script at the end of your , and then it'll work fine.

The contents inside the script tag need to be placed in some kind of function and the function needs to be called when the body loads, or else they won't run properly. Place all your Javascript code inside a load function like this:
<script>
function load() {
// rest of the code..
}
</script>
and then set the function to be called when the document loads:
<body onload="load()"> ...
Everything should then work properly.

The problem is not with your java script it is with the fact that you are writing your java script before your html.
This does not give JS enough time to load your html
An easy fix for this is to move your JS to the bottom or use something like document.ready()

I've changed Your code part with jQuery and it's sugar. It's more cross-browser solution and saves You time.
Use this:
<html>
<head>
<title>BUILD</title>
<style>
.menu > li {
display:inline-block;
font-weight:bold;
padding:6px 10px;
cursor:pointer;
border:2px solid tomato;
margin:5px;
}
.container {
border:2px solid black;
margin:5px;
}
.container > div {
display:none;
}
.container > div:first-child {
display:block;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function(){
$('.menu>li.toggle').click(function(){
$('.togglable').hide();
$('.togglable[data-id="'+$(this).data('id')+'"]').show();
});
});
</script>
</head>
<body>
<ul class="menu">
<li class="toggle" data-id="1">One</li>
<li class="toggle" data-id="2">Two</li>
<li class="toggle" data-id="3">Three</li>
<li class="toggle" data-id="4">Four</li>
<li class="toggle" data-id="5">Five</li>
</ul>
<div class="container">
<div class="togglable" data-id="1">Here are the contents of 1.</div>
<div class="togglable" data-id="2">Here are the contents of 2..</div>
<div class="togglable" data-id="3">Here are the contents of 3...</div>
<div class="togglable" data-id="4">Here are the contents of 4....</div>
<div class="togglable" data-id="5">Here are the contents of 5.....</div>
</div>
</body>
</html>

Related

Select/edit all children elements inside a div

How can I use jquery or css to assign a .class to all elements inside a div?
i.e this is what I have
<div class="nav">
one
two
</div>
But this is what I want
<div class="nav">
one
two
</div>
Using as little code as possible, so that when the page loads, the elements in .nav have the class "test" assigned to them and I don't have to assign it in every single
You can achieve this by following code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div>
one
two
</div>
</body>
<script type="text/javascript">
$(document).ready(function () {
$('div > a').addClass('test')
})
</script>
</html>
Pretty simple in jQuery: $('div a').addClass('class');
Or in JavaScript something like this:
let links = document.querySelectorAll("div a");
for(let link of links) {
link.classList.add("class");
}
.class {
text-decoration: none;
color: orange;
font-size: 50px;
margin-right: 100px;
}
<div class="nav">
one
two
</div>
$(document).ready(function() { $('.nav a').each(function(){ $(this).addClass("Test"); }) });
.Test{
color:red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav">
one
two
</div>

How can I update url with hashchange within tabs by using Javascript

I would like to get my page to display the current tab in the URL, please keep in mind I'm still learning, so my coding skills are not the greatest. I would normally use PHP for this, but I've been asked to stick to Javascript/JQuery.
So far, I've managed to get my tabs to display content dynamically within a div by using a simple script.
This is my index bit:
<div class="row">
<div class="col-md-3 col-lg-3">
<div class="custom-left-tabs -text--uppercase">
<div class="custom-left-tabs-btn hidden-lg hidden-md">
Menu<i class="fa fa-angle-down"></i>
</div>
<ul id="lefttabs" class="list-unstyled collapse">
<li class="sub-heading">Getting Started</li>
<li><a data-toggle="tab" href="pages/first.html">First</a></li>
<li><a data-toggle="tab" href="pages/second.html">Second</a></li>
</ul>
</div>
</div>
<div id="content" class="tab-content col-lg-9 -bg--white -padding--m">
</div>
</div>
This is my script:
$(document).ready(function(){
$("#content").load("pages/first.html");
});
$("li").find('a').click(function(){
var page = $(this).attr('href');
$("#content").load(page);
return false;
});
Ideally I would prefer not having all content chucked into one page. I've checked many similar questions/videos, but I can't really find the missing bit.
My question is really how should I write a script that does this extra bit of displaying the current tab on the URL.
Here this thing can be done using iframe which works well,
but as you suggested i have tried it. here is my code.
reference same as you gave before.
Now i am showing code here
use js in this manner:
<script src="jquery.min.1.4.js"></script>
<script src="jquery.blockUI.js"></script>
<script>
$(function(){
$("#tabs a").click(function(e){
$("#tabs li").removeClass("on");
$(this).parent("li"). addClass("on");
var page = this.hash.substr(1);
$("#content_wrapper").block();
$.get(page+".html",function(html){
$("#content").html(html);
$("#content_wrapper").unblock();
});
});
});
</script>
and html code with "<div>" tag.
<ul id="tabs">
<li>TAb1</li>
<li>TAb2</li>
</ul>
<div id="content_wrapper">
<div id="content">
</div>
</div>
i have also used jquery.min.js and blocjUI.js and css
css code is here
<style>
ul {
margin:0px;
padding:0px;
overflow:hidden;
}
li {
float:left;
list-style:none;
padding:10px;
background-color:#333;
border: 1px solid #ccc;
}
li a {
color: #FFF;
text-decoration:none;
font-family:arial;
}
#content_wrapper {
width:400px;
height:300px;
background-color: #ccc;
margin: 0px;
padding:6px;
overflow: hidden;
}
#content {
font-family: arial;
}
li.on {
background-color:#ccc;
}
li.on a {
color:#333;
}
and you will get two different page in one page.
Scrren1:
screen2:

How can I style links I loaded from a txt file with the jQuery load() method into my HTML?

I'm trying to load some links from a text file into a navigation menu using the jQuery AJAX load() method. It's working fine when it loads the links but it won't let me apply an active class for the current link. It applies all the other CSS for the links but not the active class. Am I missing anything?
My HTML/jQuery:
<!DOCTYPE html>
<html>
<head>
$(document).ready(function(){
$('#cat-1-button').click(function(){
$('#sec-nav-container').show();
$('#sec-nav-items').load('textfile.txt #cat-1-items');
return false;
});
$('.subCat').click(function() {
$('.subCat').removeClass('active');
$(this).addClass('active');
return false;
});
});
</head>
<body>
<div id="sec-nav-container>
<div id="sec-nav-items> </div>
</div>
<button type="button" id="cat-1-button"> Click Here </button>
</body>
</html>
Textfile:
<div id="cat-1-items">
cat1-sub1
cat1-sub2
cat1-sub3
cat1-sub4
cat1-sub5
cat1-sub6
cat1-sub7
</div>
CSS:
.active {
padding-bottom: 2px;
border-bottom: 10px solid #6b00b3;
}
You may need to add rule for pseudo-element :visited
.active,.active:visited {
padding-bottom: 2px;
border-bottom: 10px solid #6b00b3;
}
DEMO
__
Check also your html , for example, you have here some issues :
<div id="sec-nav-container"> instead of <div id="sec-nav-container>
<div id="sec-nav-items"> instead of <div id="sec-nav-items>
try this replace instead $('.subCat').click(function()...
$('#sec-nav-items').on( 'click', 'a.subCat', function(){
$('.subCat').removeClass('active');
$(this).addClass('active');
return false;
})

Javascript mouseover Element Flickers & Uncaught TypeError

I am trying to use javaScript mouseover and mousout function to get elements from the DOM. sourced child elements from that event.target and add styling to the childNode that matches the specified class name.
Issue that are occurring:
Error: Uncaught TypeError: Cannot read property 'style' of undefined
Displayed class flickers. when mouse is moved even with in the mouse Over current DOM element.
I've tried to get elements by tag name and childNodes filtered through for statemant to apply css, but still issue's
Its probably an easy fix but am baffled.
Any assistance would be great.
The HTML
<!doctype HTML>
<html>
<head>
<title>Gmail Label List</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="func.js"></script>
</head>
<body>
<div id="sideBar-left">
<div class="SbInner-body">
<ul id="label-list">
<li class="lb_li">
<div class="lb-title">Label List 1</div>
<div class="lb-a-icon">
<img src="chevron_expand.png">
</div>
</li>
<li class="lb_li">
<div class="lb-title">Label List 1</div>
<div class="lb-a-icon">
<img src="chevron_expand.png">
</div>
</li>
<li class="lb_li">
<div class="lb-title">Label List 1</div>
<div class="lb-a-icon">
<img src="chevron_expand.png">
</div>
</li>
<li class="lb_li">
<div class="lb-title">Label List 1</div>
<div class="lb-a-icon">
<img src="chevron_expand.png">
</div>
</li>
</ul>
</div>
</div>
</body>
</html>
THE CSS
body
{
background-color: #f0f0f0;
}
div#sideBar-left{
position:relative;
float:left;
width:180px;
}
div.SbInner-body{}
ul#label-list{
background-color: #898989;
width:auto;
height:auto;
overflow: hidden;
}
ul#label-list li {
list-style: none;
cursor:pointer;
background-color: #989898;
width:100%;
height:auto;
overflow: hidden;
}
div.lb-title{
position:relative;
float:left;
height:auto;
width:auto;
padding:5px;
}
div.lb-a-icon{
position:relative;
float:right;
height:15px;
padding:10px;
width:16px;
border:1px solid black;
display: none;
}
THE JS
function showLabel_icon(element)
{
element.target.getElementsByClassName('lb-a-icon')[0].style.display="block";
}
function closeLabel_icon(element)
{
element.target.getElementsByClassName('lb-a-icon')[0].style.display="none";
}
//[ Listeners]
function Add_DOM_listeners(){
if(window.addEventListener){
var lb = document.getElementById('label-list')
var lb_child = lb.getElementsByClassName('lb_li');
for(var i = 0; i < lb_child.length; i++){
lb_child[i].addEventListener('mouseover',showLabel_icon, false);
}// end for
var lc = document.getElementById('label-list')
var lc_child = lc.getElementsByClassName('lb_li');
for(var j = 0; j < lc_child.length; j++){
lc_child[j].addEventListener('mouseout',closeLabel_icon, false);
}// end for
}// end if
}//end function
window.onload = function(){
Add_DOM_listeners();
}
Suggested solution
I think that, unless there's other logic not described in the question, the entire JavaScript section can be replaced by the following CSS declaration:
/* By default the icon is not rendered: */
.lb-a-icon {
display: none;
}
/* When <li> is hovered, its icon child is displayed: */
.lb_li:hover .lb-a-icon {
display: block;
}
Demo: http://jsfiddle.net/CHTKM/
You can also play around with visibility: hidden; and visibility: visible;
Reason of TypeError
The event.target references an element the cursor is pointing to. Suppose you add the event listener to your <li> that has the following HTML structure...
<li class="lb_li">
<div class="lb-title">Label List 1</div>
<div class="lb-a-icon">
<img src="chevron_expand.png">
</div>
</li>
Now when you hover the mouse over <li> contents, the event.target could point, for example, to <div class="lb-title">Label List 1</div> which doesn't have any elements with lb-a-icon class. Attempting to get those non-existing elements results in undefined which, obviously, has no style property and thus an error is thrown.
To solve the issue you can use this (but not in IE6-8!), which references the element to which the event listener is added.
function showLabel_icon() {
// In this particular case "this" is <li class="lb_li">
this.getElementsByClassName('lb-a-icon')[0].style.display = 'block';
}
JavaScript advice
If you want to stick with JavaScript, instead of:
window.onload = function () {
Add_DOM_listeners();
}
It's much better to write:
window.addEventListener('load', add_DOM_listeners);
Doing it this way, you won't have the overhead of creating an additional function. You will also avoid inadvertently overriding any other onload listener present on your page.
Also, your Add_DOM_listeners function can be reduced to the following:
function Add_DOM_listeners() {
var labelList = document.getElementById('label-list'),
labelChildren = labelList.getElementsByClassName('lb_li'),
ii = labelChildren.length,
i;
for (i = 0; i < ii; i += 1) {
labelChildren[i].addEventListener('mouseover', showLabel_icon);
labelChildren[i].addEventListener('mouseout', closeLabel_icon);
}
}
Compatibility
For IE6-8, of course, you'll need attachEvent and window.event.srcElement.

JQuery - Changing active link color

I've got a small page with two links that load content into a div dependant upon which link is pressed.
Question is fairly obvious, i'd like to highlight the current content link with a different color and toggle the color according to which link is pressed.
I'm attempting to do this with my current function using the following however it isn't working:
Pretty simply question so i'm obviously being dumb. Any help would be much appreciated.
Thanks!
<script type="text/javascript">
function loadContent(id) {
$("#video").load("streams.php?o="+id+"");
$('active').removeClass('active');
$(this).addClass('active');
}
</script>
Full code:
<html>
<head>
<title>beam</title>
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
swfobject.registerObject("myId", "9.0.0", "expressInstall.swf");
</script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function loadContent(id) {
$("#video").load("streams.php?o="+id+"");
$('active').removeClass('active');
$(this).addClass('active');
}
</script>
<style>
* { margin:0; padding:0; }
img{ border-style:none; }
html { height: 100%; }
body { height: 100%; font-family: "Tahoma", "Arial", sans-serif; font-size:15px; font-weight: bold;}
a {
color:#fff;
text-decoration: none;
}
.active {
color:#00d2ff;
}
.container {
position:absolute;
background:url("images/video-bg.jpg") no-repeat;
width:520px;
height:576px;
}
#video {
position:relative;
background:#000;
top:275px;
left:55px;
width:400px;
height:222px;
}
#stream-controller {
position:relative;
left:55px;
top:285px;
width:200px;
}
</style>
</head>
<body onLoad="loadContent(1);">
<div id="fb-root"></div>
<div class="container">
<div id="video">
</div>
<div id="stream-controller">
<p>STREAM 1 | STREAM 2</p>
</div>
</div>
</body>
</html>
One issue is your selector for the active link:
$('active').removeClass('active');
should be:
$('.active').removeClass('active');
The other issue, though I haven't tested this yet, is that I don't believe using href="javascript:loadContent(1);" will set the value of this in the function to the appropriate a element. If you're working with jQuery, you'd be better off setting the handler with jQuery, and passing the variable through the tag, something like:
<a class="stream active" href="streams.php?o=1">STREAM 1</a>
with the jQuery code:
$(function() {
$('a.stream').click(function(e) {
var $this = $(this);
$("#video").load($this.attr('href'));
$('.active').removeClass('active');
$this.addClass('active');
// prevent default link click
e.preventDefault();
})
});
Why don't you just do it in CSS?
a {
color:#fff;
text-decoration: none;
}
a:active {
color:#00d2ff;
}
editing out a part of my solution : ninja'd and a much better one from nrabinowitz
To toggle the "active" class to the link pressed, I would do this:
var $a = $("a");
$a.click(function() {
$a.removeClass("active");
$(this).addClass("active");
});

Categories