How to highlight active nav tab in specific case - javascript

I am using this as a template for JS which selects proper nav using JQuery, with this API reference.
My current code:
index.php
<html>
<head>
<title>ChillSpot Alpha 1.2.3</title>
<link rel="stylesheet" type="text/css" href="common/style.css">
<script type="text/javascript" src="common/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="background.js"></script>
<script type="text/javascript" src="common/navHighlight.js"></script>
<script type="text/javascript"> $( document ).ready( getImage );</script>
<script type="text/javascript"> $( document ).ready( setNavigation );</script>
</head>
<?php
include 'common/header.html';
?>
//More code, snipped from example: not relevant
common/navHighlight.js
<!--
function setNavigation() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$(".menuList a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).closest('li').removeClass('tab');
$(this).closest('li').addClass('tab selected');
}
});
}
//-->
common/header.html
<div class="menu">
<ul class = "menuList">
<li class="tab">Home</li>
<li class="tab">Communications</li>
<li class="tab">ChillCraft</li>
<li class="tab">Forum</li>
<li class="tab">Updates</li>
<li class="tab">About</li>
</ul>
</div>
<div class="content">
... this isnt working. What is different in my situation that causes the example to fail? All "li" elements end up with class "tab", none have "tab selected".

I'm not sure if this is actually what's wrong, but I do notice that the href's in their example all start with / while yours do not. Relative pathing could be why yours isn't working.
So if you change your html to this you might be fine:
<div class="menu">
<ul class = "menuList">
<li class="tab">Home</li>
<li class="tab">Communications</li>
<li class="tab">ChillCraft</li>
<li class="tab">Forum</li>
<li class="tab">Updates</li>
<li class="tab">About</li>
</ul>
</div>

My approach on these cases is as follows:
Add a unique id to each of your tabs (in addition to the class you already have)
On each specific file (index.php, common.php, forum.php, etc) create an object with your selected tab:
var selected = $('#forumTab');
Execute a function where you ensure to be removing the active class from all tabs and add it only to your current tab:
$('.tab').removeClass('active');
selected.addClass('active');

Related

getting type error on occasion but not every time

I am building an e-commerce site. Right now it's basically one HTML page that filters in based on page loads and clicks. I did it this because the entire site needed to be dynamic, as I'll be tying in a show shortly.
Everything seems to work fine now that I have placed the script on the actual pages instead of in a main .js file. I get a few hiccups here and there, and I'm hoping this issue will help fix some of them.
Sometimes when I click on the view cart button it throws back a type error saying that $a.mobile.document.on is not a function. This doesn't happen all the time. I can just click the button with the shopping cart open and the cart just refreshes. As I am clicking the button, nothing in the code should be changing, everything should be flowing the exact same. Why do I get the error sometimes? There is no pattern as to how often the error occurs (i.e. every 3rd click, etc...)
My code:
<head>
<meta charset="UTF-8"/>
<title>DATique</title>
<link rel="stylesheet" href="styles.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="lib/jqm-icon-pack-fa.css">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div id="container" data-role="page" data-theme="b">
<div id="header" data-role="header">
<div id="headerGraphic"><img class="menu" src="img/products/DATique.png" alt="" align=center></div>
<!-- todo add tagline back in -->
<div data-role="footer" id="headerTagLine">an adult novelty company</div>
</div>
<div id="mainNavBar">
<div id="mainNav" data-role="navbar">
<ul>
<li class="home ui-icon-home">Home</li>
<li class="about ui-icon-question-circle">About</li>
<li class="contact ui-icon-envelope">Contact</li>
<li class="request ui-icon-lightbulb-o">Requests</li>
<li class="find ui-icon-location-arrow">Find</li>
</ul>
</div>
</div>
<div id="content" data-role="main">
<!-- todo add facebook plugin -->
<div id="sideBar">
<div id="sideNav">
<script>
</script>
</div>
</div>
<div id="productWindow">
<script>
</script>
</div>
</div>
<div data-role="footer" id="footer">
<ul>
<li id="addingItem"></li>
<li id="cartHolder">
<div class="view">View Cart</div>
<div class="cartImg"><img src="lib/png/shopping-cart.png"></div>
<div class="badge ui-corner-all"></div>
</li>
</ul>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var initialLoad = $.post('lib/aboutUs.php');
initialLoad.done(function (data) {
$('#productWindow').html(data);
});
var sideBar = $.post('lib/sideNav.php');
sideBar.done(function (data) {
$('#sideNav').html(data);
});
$('#cartHolder').unbind().click(function (data) {
var url = 'lib/cart.php';
var getCart = $.post(url);
console.log(data);
getCart.done(function (data) {
$('#content').html(data);
});
getCart.fail(function (data) {
console.log(data);
});
});
})
</script>
</body>
Here's my cart.php. The only file affected by the click event is the show cart button.
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<?php
session_start();
#$_SESSION = array();
$items = $_SESSION;
echo "<div id='showCart' class='ui-corner-all' style='max-width:400px;'>
<div data-role='header' data-theme='a' class='ui-corner-all' style='margin-top:20px;'>
<h1>Your Cart</h1>
</div>
<div role='main' class='ui-content ui-corner-all'>
<ul data-role='listview' data-split-icon='delete' data-split-theme='d'>";
foreach ($items['cart'] as $list) {
echo "<li ><a href='#'>
<img src = 'img/products/" . $list['itemNum'] . ".png'>
<h3 > " . $list['itemName'] . " </h3 >
<h1 style='text-align:right'> " . $list['price'] . "
</h1 ></a>
<a href='#' class='removeItem' name='" . $list['itemNum'] . "'>Remove Item</a>
</li >";
}
echo "</ul>
</div>
</div>"
?>
<script>
$(document).ready(function() {
console.log ("error ready");
function showCart() {
console.log("showCart Function");
var url = 'lib/cart.php';
var getCart = $.post(url);
getCart.done(function (data) {
console.log("cart received");
$('#content').html(data);
});
}
$('.removeItem').unbind().click(function () {
console.log("remove clicked");
var itemNum = {'itemNum': ($(this).attr('name'))};
var sent = $.post("lib/removeFromCart.php", itemNum);
sent.done(function () {
console.log("item removed from cart");
showCart();
});
});
});
</script>
I also have 2 other pages that have script on them that are loaded onto the home page by $.post.
Sorry if this question is easy, I just hope it isn't a period or brace somewhere. It's almost always a period or a brace. Again, looking to see if someone can tell me why this sometimes throws an error when I hit the view cart button. It seems to be doing it right after the console.log call in the cart.php.
Just a note not an answer
i had all my javascript in a myScript.js file that loaded at the bottom of the html of the main page. but none of the other pages with scipts would read the javascript on the main page for some reason until i loaded the .js file into each page.
$(document).ready(function() {
code 1
....});
$(document).ready(function() {
code 2
....});
code 1 is not able to access code 2 and vice versa, in php this is akin to this
function one(){
code 1
}
function too(){
code 2
}
One way around that is to globalize stuff, by using window. although it's not usually recommended.
var one;
var window.one;
for example( scope resolution ). Other ways involve using the DOM, by attaching to a object on the page, such as how a plugin works. for example using $(element).data('mydata', {foo:'bar'});
not sure if this was what you were saying but the explanation is way to long for a comment.

Trying to load html pages onto page

Once an li is clicked I want to load a separate html page with content on the main index page.
HTML
<nav>
<ul>
<li>Planet 1</li>
<li>Planet 2</li>
<li>Planet 3</li>
<li>Planet 4</li>
</ul>
</nav>
So once one of the links is clicked I want the jquery to load the content on the same page.
$(document).ready(function(){
// load("location-to-your-file", function(){})
//var indexCatch = $('ul li').click(function(){ alert($(this).index()); });
$("li").click(function(){
$("main").load("tab-1.html", function(){
// Instead of creating another selector combining it from $(this).hide()
// $($(this).hide()).fadeIn(1000);
// you can chain the methods:
$(this).hide().fadeIn(1000);
});
});
Its working for me,
save this file example.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Include</title>
</head>
<body>
<input type="text" id="txt_name">
<a id="link" href="#">Click Test Link</a>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$("#link").on('click',function(){
value=$("#txt_name").val();
window.location = "tab-1.php?txt_value="+value;
});
</script>
</body>
</html>
save this file tab-1.php
<b><i>Hello : <?php echo $_GET['txt_value']; ?></i></b>
You're problem is probably the fact that you are using <a> tags
you don't need them
<nav>
<ul>
<li data-href="tab-1.html">Planet 1</li>
<li data-href="tab-2.html">Planet 2</li>
<li data-href="tab-3.html">Planet 3</li>
<li data-href="tab-4.html">Planet 4</li>
</ul>
</nav>
$(document).ready(function(){
$("li").click(function () {
$("main").load(this.dataset.href, function(){
$(this).hide().fadeIn(1000);
});
});
});
Here we get the value of that specific link href attribute, and inject it into the load function
NOTE: As I can't show a demo of it using fiddle or S.O code panel, here is a DEMO showing how this code works
$(document).ready(function () {
$("nav a").each(function () {
$(this).click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
$("main").load(href).hide().fadeIn(1000);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<nav>
<ul>
<li>Planet 1
</li>
<li>Planet 2
</li>
<li>Planet 3
</li>
<li>Planet 4
</li>
</ul>
</nav>
<main></main>

retrieving an element/text after it's been clicked

I have 5X5 text box with letters that randomly change every few seconds. I figured out how to make the box selectable. Now I want to be able to retrieve the letter that's appearing within the box at the time that I click. I'm new to coding, but after researching, I thought I could combine the .click function with the .text() function. I add a tag and tried to print the clicked letter within it. It's not working. I'm I using the .text() function incorrectly? I haven't used it before so I'm not sure.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>LetterTouch</title>
</head>
<link rel = "stylesheet" type="text/css" href="gameboard.css">
<!-- <link href="scripts/jquery-ui-1.10.4.custom.css" rel="stylesheet" type="text/css"/>-->
<script type="text/javascript" src="scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$("#squares").selectable();
});
var nIntervId;
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function changeLetters() {
nIntervId = setInterval(boardGen, 1500);
}
function boardGen() {
$('li').each(function (i, e) {
$(e).text(letters.charAt(Math.floor(Math.random() * letters.length)));
})
}
$( "li" ).click(function() {
$( this ).text();
$( "p" ).html( );
});
changeLetters();
</script>
<body>
<ol id="squares">
<li class="A1"></li>
<li class="A2"></li>
<li class="A3"></li>
<li class="A4"></li>
<li class="A5"></li>
<li class="B1"></li>
<li class="B2"></li>
<li class="B3"></li>
<li class="B4"></li>
<li class="B5"></li>
<li class="C1"></li>
<li class="C2"></li>
<li class="C3"></li>
<li class="C4"></li>
<li class="C5"></li>
<li class="D1"></li>
<li class="D2"></li>
<li class="D3"></li>
<li class="D4"></li>
<li class="D5"></li>
<p> H </p>
</body>
</html>
Might be this is what you are trying to do http://jsfiddle.net/jogesh_pi/X24s9/
$("document").ready(function() {
$("#squares").selectable();
$( "#squares" ).on('click', 'li', function() {
var txt = $( this ).text();
$("p").html(txt);
});
});
Just pass the text of that clicked li element as the parameter of html() function gonna be run on behalf of the p tag.
Try,
$("#squares li").click(function() {
$("p").html($(this).text());
});
And also your html seems invalid, please try to close that <ol> tag
Since you're inserting the characters inside the li, you will want to use .text() to pick them up.
e.g.
$( "li" ).click(function() {
$( "p" ).html($(this).text());
});
what this does is that I took the html content of the li - referenced by $(this).text(), and assigned that to be the content of the p element. How .html() works is that placing a string parameter in it assigns that to its html content.
Simply use the .text() property.
$("p").html($(this).text());

get order of items jquery sortable and set order to them

I use jquery draggble function for unorderd list (ul) and face a problem of getting the order of items after it changed and setting the order ofter page is loaded.Suppose we have the following code :
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$(".block").sortable({
axis: 'y',
update: function(event, ui) {// order changed
var order = jQuery(this).sortable('toArray');
// send this order to index.php and store it in db
}
});
});
</script>
</head>
<body>
<ul class="block" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
</body>
and the second file is
<html>
<head>
<script>
$('.secondblock').sortable({axis:'y'});
// get order from index.php and set it to .secondblock
</script>
</head>
<body>
<ul class="secondblock" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
</body>
</html>
Are there any possible solutions?
If you don't want to use that solution on the link I've commented, you can use this, much simpler:
function reorder(orderArray, elementContainer)
{
$.each(orderArray, function(key, val){
elementContainer.append($("#"+val));
});
}
orderArray: an array containing all ids in the order you want ( exactly what sortable( "toArray") returns)
elementContainer: is the jQuery object which contains your sortable items.
A working example here:
http://jsfiddle.net/ecP5k/1/

Getting Twitter Bootstrap's "Tabs" Javascript to Work on Rails App

A javascript problem on a rails app.
Twitter docs keep things very straightforward, however I'm still unable to get tabs to work dynamically (tab switching and dropdown). I straight up copied their source code and downloaded their javascript and included that in my application.js file on my rails app. Not sure what I'm missing.
The HTML file:
<script>
$(function () {
$('#.tabs').bind('change', function (e) {
e.target // activated tab
e.relatedTarget // previous tab
})
</script>
<h3>Demo</h3>
<ul class="tabs" data-tabs="tabs">
<li class="active">Home</li>
<li>Profile</li>
<li>Messages</li>
<li>Settings</li>
<li class="dropdown" data-dropdown="dropdown">
Dropdown
<ul class="dropdown-menu">
<li>#fat</li>
<li>#mdo</li>
</ul>
</li>
</ul>
<div id="my-tab-content" class="tab-content">
<div class="active tab-pane" id="home">
<p>Lorem Ipsum.</p>
The Application.js file:
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(document).ready(function(){
!function( $ ){
"use strict"
function activate ( element, container ) {
container
.find('> .active')
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if ( element.parent('.dropdown-menu') ) {
element.closest('li.dropdown').addClass('active')
}
}
function tab( e ) {
var $this = $(this)
, $ul = $this.closest('ul:not(.dropdown-menu)')
, href = $this.attr('href')
, previous
, $href
if ( /^#\w+/.test(href) ) {
e.preventDefault()
if ( $this.parent('li').hasClass('active') ) {
return
}
previous = $ul.find('.active a').last()[0]
$href = $(href)
activate($this.parent('li'), $ul)
activate($href, $href.parent())
$this.trigger({
type: 'change'
, relatedTarget: previous
})
}
}
/* TABS/PILLS PLUGIN DEFINITION
* ============================ */
$.fn.tabs = $.fn.pills = function ( selector ) {
return this.each(function () {
$(this).delegate(selector || '.tabs li > a, .pills > li > a', 'click', tab)
})
}
$(document).ready(function () {
$('body').tabs('ul[data-tabs] li > a, ul[data-pills] > li > a')
})
}( window.jQuery || window.ender );
});
you don't need the first script (it's included in the documentation as an example only, in case you want more than what comes in the box)
what you do need is a link to the bootstrap stylesheet:
<link rel="stylesheet" href="your_bootstrap_folder/bootstrap.min.css">
and two scripts (assuming you have jquery otherwise include that first):
<script type="text/javascript" src="your_bootstrap_folder/js/bootstrap-tabs.js"></script>
<script type="text/javascript" src="your_bootstrap_folder/js/bootstrap-dropdown.js"></script>
and finally the function call
<script>
$(function () {
$('.tabs').tabs()
})
</script>
that should do the trick.
EDIT: just to make sure you've got the sequence right, here's a full example:
<!DOCTYPE html>
<html>
<head>
<title>bootstrap tabs test</title>
<link rel="stylesheet" href="path_to_bootstrap/bootstrap.min.css">
</head>
<body>
<ul class="tabs">
<li class="active">Home</li>
<li>Profile</li>
<li>Messages</li>
<li>Settings</li>
<li>Contact</li>
<li data-dropdown="dropdown" class="dropdown">
<a class="dropdown-toggle" href="#">Dropdown</a>
<ul class="dropdown-menu">
<li>Secondary link</li>
<li>Something else here</li>
<li class="divider"></li>
<li>Another link</li>
</ul>
</li>
</ul>
<script type="text/javascript" src="path_to_jquery/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="path_to_bootstrap/js/bootstrap-tabs.js"></script>
<script type="text/javascript" src="path_to_bootstrap/js/bootstrap-dropdown.js"></script>
<script>
$(function () {
$('.tabs').tabs()
})
</script>
</body>
</html>
I fired up the javascript console on Chrome and realized that my scripts weren't being loaded. This is because on rails, you don't need to include the "public" file in your path to load the javascript; only is needed.
In addition, in the application.hmtl.erb file, <%= javascript_include_tag 'bootstrap-dropdown.js' %> must be included as :default does not load these js files.

Categories

Resources