adding .className to object is not working - javascript

I am attempting to set a className to my nav element and it isn't working as intended. When I manually add the class to my HTML it puts a border around the unordered list items and the buttons. When I use js to add it, it shows that the nav tag has the attribute in the inspector but it does not add the border so I do not believe it is working. What am I doing wrong? I have linked to the bootstrap cdn and jquery cdn in the file.
HTML
<!doctype html>
<html lang="en-us">
<head>
<title>Exercise 5.9</title>
<meta charset="UTF-8">
<meta equiv="X-UA-Compatible" content="IE=Edge">
</head>
<body id="content">
<!-- Latest compiled and minified CSS -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<nav>
<div>
<ul>
<li>Home</li>
<li>Our Policies</li>
<li>How you can help</li>
<li>What we have accomplished</li>
<button type="button">Donate $10.00</button>
<button type="button">Donate $50.00</button>
<button type="button">Donate $100.00</button>
</ul>
</div>
</nav>
<p>If you would to offer financial support, please choose the buttons above</p>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="exercise-5.9.js"></script>
</body>
</html>
JS
var nav = document.getElementsByTagName("nav");
nav.className = "navbar navbar-default";
console.log(nav);

Instead of using .className = try just setting the attribute of class to whatever you want. The main reason why it's not working, however, is because .getElementsByTagName() returns an array (nodeList) so you need to make sure when you set the class, it's properly indexed.
Using .setAttribute("atr", "value")
var button = document.getElementById("btnGo");
button.onclick = function () {
var nav = document.getElementsByTagName("nav");
for (var i = 0; i < nav.length; i++) {
nav[i].setAttribute("class", "myClassName");
}
};
Using .className
var button = document.getElementById("btnGo");
button.onclick = function () {
var nav = document.getElementsByTagName("nav");
for (var i = 0; i < nav.length; i++) {
nav[i].className = "myClass";
}
};

getElementsByTagName() return an array, you should write document.getElementsByTagName('nav')[0];

Related

Countdown clicker - JS

I'm totally lost as to where to begin here, how would I create a countdown button so that each time my button is clicked, it prints out the global variable and reduce it by 1 in the innerHTML and when it hits 0 it says BOOM?
I know I have to declare the variable outside but not sure what to do afterwards
JS:
var i = 20
function myFunction()
{
i = i--; // the value of i starting at 20
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 6 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script src="task6.js" type="text/javascript"></script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Count Down </p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
</body>
</html>
I tryed this code and works fine
var i = 20;
function myFunction() {
myData = document.getElementById("mydata");
i = i - 1;
myData.textContent = i;
if(i <= 0) {//with <=0 the user if click again,after zero he sees only BOOM
myData.textContent = "BOOM!"
}
}
html code
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 6 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script src="task6.js" type="text/javascript"></script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Count Down </p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 6 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script type="text/javascript">
var i = 20;
function myFunction() {
var myData = document.getElementById("mydata");
i = i - 1;
myData.textContent = i;
if(i <= 0) {
myData.textContent = "BOOM!"
}
}
</script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Count Down </p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
</body>
</html>
It's good practice to not inline JS in the HTML so I'll provide an extra example to show how to separate it out using a couple of DOM selection methods:
let count = 20;
// grab the element with the mydata id
const mydata = document.getElementById('mydata');
// grab the button and attach an click event listener to it -
// when the button is clicked the `handleClick` function is called
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
function handleClick() {
if (count === 0) {
mydata.textContent = 'Boom';
} else {
mydata.textContent = count;
}
count--;
}
<body>
<p id="mydata">Countdown</p>
<button>Click</button>
<script src="task6.js" type="text/javascript"></script>
</body>
Reference
getElementById
querySelector
addEventListener
I'll assume you want to show the variable output and the BOOM at the <p id="mydata"> Count Down </p>, if I am mistaken correct me. So, something like this:
let i = 20;
const myData = document.querySelector("#mydata");
function myFunction() {
i = i - 1;
myData.textContent = i;
if(i === 0) {
myData.textContent = "BOOM!"
}
}
You almost got it whole,only missed the textContent and if part. If this is what you wanted to achieve. If this isn't what you were looking for, hit me up so I can correct it. Cheers :)
You need some way of displaying the number inside of your variable. One of the simplist ways to do this would be to set text to your paragraph tag using getElementById() and inner HTML. For example, after running your deincrement, on the next line you would do something like...
function myFunction()
{
i = i--; // the value of i starting at 20
document.getElementById("mydata").innerHTML = i;
}
This code simply grabs your "mydata" paragraph from the DOM and injects the number into the tag as html.

Materializecss sidenav not working

I am trying to get the sidenav to work for the Materializecss framework.
MATERIALIZECSS http://next.materializecss.com/getting-started.html
SIDENAV DEMO http://next.materializecss.com/sidenav.html
MY CODEPEN https://codepen.io/gregoryksanders/pen/RxoyqB
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/
</head>
<body>
<ul id="slide-out" class="sidenav">
<li><i class="material-icons">cloud</i>First Link With Icon</li>
<li>Second Link</li>
<li><div class="divider"></div></li>
<li><a class="subheader">Subheader</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
<i class="material-icons">menu</i>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/js/materialize.min.js"></script>
</body>
3 Days trying to figure this out :/ so any help is welcomed.
The problem is that you should initialize the side-nav in Javascript code like this
var elem = document.querySelector('.sidenav');
var instance = new M.Sidenav(elem);
// with jquery
$(document).ready(function(){
$('.sidenav').sidenav();
});
now your code will work perfect
var elem = document.querySelector('.sidenav');
var instance = new M.Sidenav(elem);
// Initialize collapsible (uncomment the lines below if you use the dropdown variation)
// var collapsibleElem = document.querySelector('.collapsible');
// var collapsibleInstance = new M.Collapsible(collapsibleElem, options);
// Or with jQuery
$(document).ready(function(){
$('.sidenav').sidenav();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/js/materialize.min.js"></script>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/
</head>
<body>
<ul id="slide-out" class="sidenav">
<li><div class="user-view">
<div class="background">
<img src="images/office.jpg">
</div>
<img class="circle" src="images/yuna.jpg">
<span class="white-text name">John Doe</span>
<span class="white-text email">jdandturk#gmail.com</span>
</div></li>
<li><i class="material-icons">cloud</i>First Link With Icon</li>
<li>Second Link</li>
<li><div class="divider"></div></li>
<li><a class="subheader">Subheader</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
<i class="material-icons">menu</i>
<!-- Compiled and minified JavaScript -->
</body>
On the materialize website, this code is given to initialize Sidenav bar
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems, options);
});
but You modify This code and remove option in var instance and now code look like and you should paste this code in your script tag or your javascript file
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
Now I explain what is the problem in upper code that given on the materialize website
in code, variable instances give 2 arguments 1st argument is elems and 2nd argument is the option that is not defined in your code so you remove the option argument in this code to solve this problem
Initialization is the most important thing when using materialize.js, for example i want to initialize a carousel.
// Javascript
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.carousel');
var instances = M.Carousel.init(elems, options);
});
// Or with jQuery
$(document).ready(function(){
$('.carousel').carousel();
});

Navigation between pages - html

I trying to navigate between 3 pages which contain the same header and footer but each page has different content.
I want to load different contents html on hash change.
The problem is that when I click on the same page again, the content.html loaded again.
How can I use the content without loading the html again and again, using java script/html/jquery?
Code example:
Navigationbar.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Navigation Bar</title>
<link rel="stylesheet" type="text/css" href="css/navigationbar.css">
</head>
<body>
<nav>
<img id="navigation-bar-logo" class="logo" src='images/flybryceLogo.png'>
<ul class="navigation-bar-ul">
<li class="navigation-bar-li"><a id="navigation-bar-contact-page-tab" href="#contact.html">CONTACT</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-about-us-page-tab" href="#aboutus.html">ABOUT US</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-home-page-tab" href="#home.html">HOME</a></li>
</ul>
</nav>
</body>
</html>
initial.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>One Page Test</title>
<link rel="stylesheet" type="text/css" href="css/homepage.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="main-container" class="main-container">
<div id="header" class="header">
</div>
<div id="content" class="content"></div>
<div id="footer" class="bot"></div>
</div>
<script>
document.onreadystatechange = function(){
if (document.readyState == 'complete') {
window.onhashchange=hash_change;
window.onload=hash_change;
if(window.location.hash==''){
//default hash
window.location.replace('#home.html');
}
//load the header
$("#header").load("fragments/navigationbar.html");
//load the footer
$("#footer").load("fragments/footer.html");
}
}
function hash_change()
{
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
$("#content").load("home.html");
} else if (newHashCode === "aboutus.html") {
$("#content").load("aboutus.html");
} else if (newHashCode === "contact.html"){
$("#content").load("contact.html");
}
}
</script>
</body>
</html>
A longer but suitable solution would be to build a content cache on your own.
For example asking to the server just once the html and then setting it to the $('#content') element. You can use this helper function.
var contentsCache = {};
var getAndCache = function(url, callback) {
var cachedContents = contentsCache[url];
if (!cachedContents) {
$.get(url, function(serverContents) {
cachedContents = serverContents;
contentsCache[url] = cachedContents;
callback(cachedContents);
});
} else {
callback(cachedContents);
}
};
And then replace the $('#content').load calls by calls to this new asynchronous way.
function hash_change()
{
var fillContentCb = function(s) {
$('#content').html(s);
};
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
getAndCache("home.html", fillContentCb);
} else if (newHashCode === "aboutus.html") {
getAndCache("aboutus.html", fillContentCb);
} else if (newHashCode === "contact.html"){
getAndCache("content.html", fillContentCb);
}
}
As suggested in some comments, consider using native HTML navigation instead. Another suggestion is to use a client-side JS framework which supports routing if this application is likely to grow.
Add an if condition that checks whether the current hash location matches with the one that's been clicked on, and if it does just return. You'd have to store it in a global JS variable, and set it every time you navigate.

how The JQuery ui Tabs to dynamically created elements?

Hello I have the following hml page.
I need to apply the jQuery ui Tabs plugin to the dynamically added elements.
how can I get that.
please note that when I add <li> elements as string that work fine but when i use document.createElement it dont work instead I get the same html structure when I inspect these elements
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Tabs - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="http:/resources/demos/style.css">
</head>
<body>
<div id="tabs">
<ul>
<li>Sample0</li>
</ul>
<div id="tabs0">
<p>exemple1</p>
</div>
</div>
<input type="button" onclick="ReloadTabs()" value="rebuild"/>
<script>
$(function() {
$("#tabs").tabs();
});
//add tabs and recreate my tabs
function ReloadTabs() {
var liElement1 = document.createElement('li');
var anchElement1 = document.createElement('a');
$(anchElement1).attr("href", "tab1");
$(liElement1).append(anchElement1);
var liElement2 = document.createElement('li');
var anchElement2 = document.createElement('a');
$(anchElement2).attr("href", "tab2");
$(liElement2).append(anchElement2);
$("#tabs ul").append(liElement1);
$("#tabs ul").append(liElement2);
$("#tabs").append('<div id="tab1"><p>sample1</p></div><div id="tab2"><p>.</p><p>Sample2</p></div>');
$("#tabs").tabs("refresh");
}
</script>
</body>
</html>
you can try like this
change html for your button
<input type="button" id="rebuild" value="rebuild"/>
change your js code
$(function() {
$("#tabs").tabs();
$(document).on('click', '#rebuild', function() {
var ul = $('#tabs').find('ul');
var liElement1 = $('<li />');
$(liElement1).append('<a href="#tab1" >tab1</a>');
var liElement2 = $('<li />');
$(liElement2).append('<a href="#tab2" >tab2</a>');
$(ul).append(liElement1);
$(ul).append(liElement2);
$("#tabs").append('<div id="tab1"><p>sample1</p></div><div id="tab2"><p>.</p><p>Sample2</p></div>');
$("#tabs").tabs("refresh");
});
});
also check in jsfiddle
http://jsfiddle.net/0jp0xpmu/1/
I am not sure but i think it's helpful to you.

unable to bind image to img tag

I am practicing Windows Phone development using WinJS and I have the following code which parses JSON received from a particular URL. And using the images to be bound to a list view in an HTML page,
JavaScript code:
WinJS.xhr({ url: urlToBeUsed }).then(
function (sportsResponse) {
var sportsJSON = JSON.parse(sportsResponse.responseText);
var listItems = sportsJSON.Videos.Data;
for (var i = 0; i < listItems.length; i++) {
var imageList = listItems[i].Items;
var count = imageList.length;
if (count > 0) {
listItems[i].Items[0].Images.forEach(imageIteration);
function imageIteration(value, index, array) {
var picture = value.Url;
var name = value.title;
sportsImageList.push({
title: name,
picture: picture
});
}
}
}
imageList.itemDataSource = sportsImageList.dataSource;
})
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- WinJS references -->
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<script src="/js/navigator.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<link href="/pages/home/home.css" rel="stylesheet" />
<script src="/pages/sports/sports.js"></script>
</head>
<body>
<!-- The content that will be loaded and displayed. -->
<div class="fragment homepage" style="width:100%;height:100%;padding:10px">
<div class="myTemplate" data-win-control="WinJS.Binding.Template">
<div class="myItem">
<img data-win-bind="src:picture" style="width:100px;height:100px" />
</div>
</div>
<div id="imageList" data-win-control="WinJS.UI.ListView" data-win-bind="winControl.itemDataSource:sportsImageList.dataSource" data-win-options="{itemTemplate:select('.myTemplate')}"></div>
</div>
</body>
</html>
I have tried many ways to bind the URL to the Image, but on the screen I can only see the links but not the actual images.
Where am I wrong?
All help and suggestions appreciated.
Thank you!
I believe your error is in your assignment line, remember that itemDataSource is a property of the ListView control. As it is in your code you're assigning that property to the imageList element.
Change it to this:
imageList.winControl.itemDataSource = sportsImageList.dataSource;

Categories

Resources