I've been having the same issue for a very long time and I'm wondering if someone can teach me what I'm doing wrong.
I created a multipage Jquery (like the one in the example below) however, when I go to add a reference to a .js file I've saved it always tends to either not load up the pages content or if positions somewhere else it just simply wont work!
My HTML code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Find A Deal</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style>
img.fullscreen {
max-height: 100%;
max-width: 100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$("#list").empty();
var url="http://localhost/tmp/json4.php";
$.getJSON(url,function(json){
//loop through deals
$.each(json.deals,function(i,dat){
$("#list").append("<li><a id='"+dat.dealid+"' data-restaurantid=" + dat.restaurantid + " data-image=" + dat.image + "><h1>"+dat.name+"</h1><h6>"+dat.dname+"</h6><h5>"+dat.description+"</h5></a></li>");
$(document).on('click', '#'+dat.dealid, function(event){
if(event.handled !== true) // This will prevent event triggering more then once
{
dealObject.dealID = $(this).attr('id');
dealObject.restaurantid = $(this).attr('data-restaurantid');
dealObject.shortName = $(this).find('h1').html();
dealObject.image = $(this).attr('data-image');
//dealObject.dname = $(this).find('input').html();
//dealObject.dname = $(this).find('desc').val();
dealObject.dealName = $(this).find('h6').html();
dealObject.description = $(this).find('h5').html();
//dataObject.dname=$(this).find('p').html()
//dealObject.name = $(this).find('desc').eq(0).val(dealObject.name);
$.mobile.changePage( "#index2", { transition: "slide"} );
event.handled = true;
}
});
});
$("#list").listview('refresh');
});
});
$(document).on('pagebeforeshow', '#index2', function(){
//$('#index2 [data-role="content"]').html('You have selected Link' + dealObject.dname);
$('#index2 [data-role="content"]').find('#deal-img').attr('src',dealObject.dealObject);
$('#index2 [data-role="content"]').find('#title').html(dealObject.name);
//$('#index2 [data-role="content"]').find('#description').html(dealObject.dname);
$('#index2 [data-role="content"]').find('input#desc').val(dealObject.description);
$('#index2 [data-role="content"]').find('input#tname').val(dealObject.dealName);
$('#index2 [data-role="content"]').find('input#dealid').val(dealObject.dealID);
});
var dealObject = {
dealID : null,
restaurantid : null,
shortName : null,
image : null,
dealName : null,
description: null
}
</script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<h1>Current Deals</h1>
</div>
<div data-role="content">
<div class="content-primary">
<ul id="list" data-role="listview" data-filter="true"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</div>
</div>
</div>
<!--New Page -->
<div data-role="page" id="index2">
<!--<script src="js/ammend.js"></script>--!>
<div data-role="header">
<h1> Find A Deal </h1>
</div>
<div data-role="content">
<!-- <?php
if( !isset( $_SESSION ) ){
session_start();
}
if( isset( $_SESSION['username'] ) ){
echo ".";
} ?> --!>
<form id="test">
<label for="name">Deal Name:</label>
<input type="text" value="" name="tname" id="tname"/>
<label for="desc">Description</label>
<input type="text" value="" name="desc" id="desc"/>
<a data-role="button" id="amend" data-icon="star" data-iconpos="left">Amend Deal </a>
<input type="text" value="" name="dealid" id="dealid"/>
<h3></h3>
<!--<img src="" width="100px" height="100px" id="deal-img">
<h1 id="title"></h1>
<h3 id="description"></h3>
<p id="name"></p>--!>
</div>
<footer data-role="footer" data-position="fixed">
<nav data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</nav>
</footer>
</div>
</body>
</html>
Apologies if it's hard to read. This javascript function will work just fine by itself. When an item in index is clicked it brings you to a new page in index2. On index 2 there's a submit button to which is connect to a file referenced <script src="js/ammend.js"></script>. This is where things normally seem to go wrong for me as it's like they're cancelling eachother out or just not co-operating together.
The js file at that location is:
$(document).on('pagebeforeshow', '#index2', function(){
$('#amend').on('click', function(){
if($('#tname').val().length > 0 && $('#desc').val().length > 0 && $('#dealid').val().length > 0){
userObject.tname = $('#tname').val(); // Put username into the object
userObject.desc = $('#desc').val(); // Put password into the object
userObject.dealid = $('#dealid').val();
// Convert an userObject to a JSON string representation
var outputJSON = JSON.stringify(userObject);
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
ajax.sendRequest({action : 'index2', outputJSON : outputJSON});
} else {
alert('Please fill all nececery fields');
}
});
});
$(document).on('pagebeforeshow', '#index2', function(){
if(userObject.name.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
$.mobile.changePage( "#index2", { transition: "slide"} ); // In case result is true change page to Index
}
$(this).find('[data-role="content"] h3').append('Deal Amended:' + userObject.name); // Change header with added message
//$("#index").trigger('pagecreate');
});
// This will be an ajax function set
var ajax = {
sendRequest:function(save_data){
$.ajax({url: 'http://localhost/test/login/amend.php',
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (num) {
if(num == "true") {
$.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
} else {
alert('Deal has been added successfully'); // In case result is false throw an error
$.mobile.changePage( "#index", { transition: "slide"} );
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Error: " . mysql_error() . "Query: " . $query;');
}
});
}
}
// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
tname : "",
desc : "",
dealid: ""
}
The above should be called when the button is being pressed but most of the time I cant even get to the stage of seeing the button once I add the referecne to this code.
If anybody has had the same issue as this before or can shed some light on the problem I'd really appreciate it.
Your problem is related to jQuery Mobile page handling.
Because you are using multiple HTML pages loaded with ajax into the DOM all your js scripts must be referenced from the first HTML files. All other HTML files will be loaded only partially, only BODY part will be loaded while HEAD is going to be discarded.
Related
I am a student and am having an issue getting information on the correct lists. My sample data has a male runner and a female runner. I have three lists of runners: male, female, all. When I run my code, nothing appears on the male and female lists but all do show up on the "all" list. What modification do I need to get the runners on the appropriate gender lists?
function getXMLRacers() {
$.ajax({
url: "finishers.xml",
cache: false,
dataType: "xml",
success: function (xml) {
// Empty lists to prevent duplication.
$("#finishers_m").empty();
$("#finishers_f").empty();
$("#finishers_all").empty();
// Place runner name on appropriate lists.
$(xml).find("runner").each(function () {
var info = "<li>Name: " + $(this).find("fname").text() + " " +
$(this).find("lname").text() + ". Time: " + $(this).find("time").text() + "</li>";
if ($(this).find("gender").text === "m") {
$("#finishers_m").append(info);
} else if ($(this).find("gender").text === "f") {
$("#finishers_f").append(info);
} else { }
$("#finishers_all").append(info);
});
getTime();
}
});
};
My sample data in an XML file:
<?xml version="1.0" encoding="utf-8"?>
<finishers>
<runner>
<fname>John</fname>
<lname>Smith</lname>
<gender>m</gender>
<time>25:31</time>
</runner>
<runner>
<fname>Jane</fname>
<lname>Smith</lname>
<gender>f</gender>
<time>26:01</time>
</runner>
</finishers>
My html file where the lists are defined:
<!DOCTYPE html>
<html>
<head>
<title>NTC Race Finishers</title>
<link href="styles/my_style.css" rel="stylesheet">
</head>
<body>
<header>
<h2>NTC Race Finishers!</h2>
</header>
<div id="main">
<ul class="idTabs">
<li>Male Finishers</li>
<li>Female Finishers</li>
<li>All Finishers</li>
</ul>
<div id="male">
<h4>Male Finishers</h4>
<ul id="finishers_m"></ul>
</div>
<div id="female">
<h4>Female Finishers</h4>
<ul id="finishers_f"></ul>
</div>
<div id="all">
<h4>All Finishers</h4>
<ul id="finishers_all"></ul>
</div>
</div>
<footer>
<h4>Congratulations to all our finishers!</h4>
<button id="btnStart">Start Page Updates</button>
<button id="btnStop">Stop Page Updates</button>
<br>
<span id="freq"></span>
<br><br>
Last Updated: <div id="updatedTime"></div>
</footer>
<script src="scripts/jquery-3.4.1.min.js"></script>
<script src="scripts/jquery.idTabs.min.js"></script>
<script src="scripts/my_scripts.js"></script>
</body>
</html>
#DJB I think the problem lies somewhere within the following code
if ($(this).find("gender").text === "m") {
$("#finishers_m").append(info);
} else if ($(this).find("gender").text === "f") {
$("#finishers_f").append(info);
} else { }
try changing code so that you are not dependent on $(this).find("gender").text then try debugging from there. If you can provide more information than stackoverflow will be more helpful.
I found the problem. When calling the text function within the following if statement, I failed to add () after the word text. The correct code is:
if ($(this).find("gender").text() === "m") {
$("#finishers_m").append(info);
} else if ($(this).find("gender").text() === "f") {
$("#finishers_f").append(info);
} else { }
$("#finishers_all").append(info);
I have spent the better half of a day looking for an answer to this problem, I can just not wrap my head around it. I have an Index.php that requires the head element.
Head element:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="requires/style.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="requires/scripts.js"></script>
<title>Frontends</title>
</head>
<body>
<div class="grid-container">
<div class='header' style="background-color: #0059B3;">
<a href='index.php'>
<img src="assets/hhe logo.PNG"/>
</a>
</div>
This is required into the index.php file, this file looks like so:
<?php
require_once 'requires/head.html';
require 'requires/connect.php';
$string = "";
?>
<script type="text/javascript">
</script>
<div class='content' style='border-radius: 4px;'>
<div class="formcentre">
<input class="searchform" type="text" id="search" placeholder="Søger så snart du skriver." onkeyup="submitter();" autocomplete="off"/>
</div>
<div class='menu' style=' margin-top:10px;'>
<dl>
<dt>Tilføj</dt>
<dd>
<a href='opret.php'>Artikel</a><br>
Enhed<br>
Kategori<br>
</dd>
<dt>Slet</dt>
<dd>
Enhed<br>
Kategori
</dd>
</dl>
</div>
<table id="results">
</table>
⌃
</div>
</div>
<script type="text/javascript" src="requires/scripts.js"></script>
</body><!--Is opened in the reuired head.html-->
</html><!--Is opened in the reuired head.html-->
There is ofcourse a scripts.js file that looks like this:
function goBack() {
window.history.back();
}
function submitter() {
var search = document.getElementById("search").value;
/*AJAX the searchstring*/
$.ajax({
type: 'post',
url: 'ajax/searcher.php',
data: { searchString : search },
success: function(response){
$('#results').html(response);
}
});
return false;
}
$(document).ready(
function submitter() {
var search = document.getElementById("search").value;
/*AJAX the searchstring*/
$.ajax({
type: 'post',
url: 'ajax/searcher.php',
data: { searchString : search },
success: function(response){
$('#results').html(response);
}
});
return false;
}
function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 20) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
This all fine and well, I suffer from the problem that I get this specific error when i try to search for anything:
Uncaught ReferenceError: submitter is not defined at HTMLInputElement.onkeyup (index.php:27)
So the question is: should I not be able to do it this way?
Edit:
I would like to add that, apparently the browser may cache a JS file. So, yeah clear the cache. that's what actually did the trick including point number four on the marked solution. Thank you very much for the help.
Please, let's do two things:
Do not mix JavaScript and jQuery (although both are JavaScripts).
Use unobtrusive code.
These are the changes I have done:
Remove the onkeyup from the element:
<input class="searchform" type="text" id="search" placeholder="Søger så snart du skriver." autocomplete="off"/>
Add the event listener using the document's ready event:
$(function () {
$("#search").keyup(function () {
submitter();
});
});
Still better, you can do it this way:
$(function () {
$("#search").keyup(submitter);
});
Thanks to Chris G.
Use a single way:
function submitter() {
$.ajax({
type: 'post',
url: 'ajax/searcher.php',
data: {
searchString: $("#search").val()
},
success: function(response) {
$('#results').html(response);
}
});
return false;
}
Remove the duplicate occurrences of submitter() function definition. Just have only one inside the document's ready event.
I am trying to use paginate() to achieve infinite scroll. I think the easiest way is using the 'infinite-scroll' to achieve this. If you have any other suggestion how to do it without infinite-scroll library, just using jQuery, I'd be happy to know..
I am returning the variable to view like this:
public function index()
{
$posts = Post::with('status' == 'verified')
->paginate(30);
return view ('show')->with(compact('posts'));
}
My View:
<div id="content" class="col-md-10">
#foreach (array_chunk($posts->all(), 3) as $row)
<div class="post row">
#foreach($row as $post)
<div class="item col-md-4">
<!-- SHOW POST -->
</div>
#endforeach
</div>
#endforeach
{!! $posts->render() !!}
</div>
Javascript Part:
$(document).ready(function() {
(function() {
var loading_options = {
finishedMsg: "<div class='end-msg'>End of content!</div>",
msgText: "<div class='center'>Loading news items...</div>",
img: "/assets/img/ajax-loader.gif"
};
$('#content').infinitescroll({
loading: loading_options,
navSelector: "ul.pagination",
nextSelector: "ul.pagination li:last a", // is this where it's failing?
itemSelector: "#content div.item"
});
});
});
However, this doesn't work. The ->render() part is working because I am getting [<[1]2]3]>] part. However, the infinite scroll doesn't work. I also don't get any errors in the console.
[<[1]2]3]>] is like this in the view:source:
<ul class="pagination">
<li class="disabled"><span>«</span> </li> // «
<li class="active"><span>1</span></li> // 1
<li>2</li> // 2
<li>3</li> // 3
<li>»</li> // »
</ul>
Easy and helpful is this tutorial - http://laraget.com/blog/implementing-infinite-scroll-pagination-using-laravel-and-jscroll
Final script could looks like this one
{!! HTML::script('assets/js/jscroll.js') !!}
<script>
$('.link-pagination').hide();
$(function () {
$('.infinite-scroll').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="/imgs/icons/loading.gif" alt="Loading..." />', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.infinite-scroll',
callback: function() {
$('.link-pagination').remove();
}
});
});
</script>
You just need to use laravel's pagination
{!! $restaurants->links() !!}
You should be able to use the Pagination just fine as long as your call to get new posts is different than page load. So you'd have two Laravel calls:
1.) To provide the template of the page (including jQuery, CSS, and your max_page count variable -- view HTML)
2.) For the AJAX to call posts based on the page you give it.
This is how I got my infinity scroll to work...
HTML:
<!-- Your code hasn't changed-->
<div id="content" class="col-md-10">
#foreach (array_chunk($posts->all(), 3) as $row)
<div class="post row">
#foreach($row as $post)
<div class="item col-md-4">
<!-- SHOW POST -->
</div>
#endforeach
</div>
#endforeach
{!! $posts->render() !!}
</div>
<!-- Holds your page information!! -->
<input type="hidden" id="page" value="1" />
<input type="hidden" id="max_page" value="<?php echo $max_page ?>" />
<!-- Your End of page message. Hidden by default -->
<div id="end_of_page" class="center">
<hr/>
<span>You've reached the end of the feed.</span>
</div>
On page load, you will fill in the max_page variable (so do something like this: ceil(Post::with('status' == 'verified')->count() / 30);.
Next, your jQuery:
var outerPane = $('#content'),
didScroll = false;
$(window).scroll(function() { //watches scroll of the window
didScroll = true;
});
//Sets an interval so your window.scroll event doesn't fire constantly. This waits for the user to stop scrolling for not even a second and then fires the pageCountUpdate function (and then the getPost function)
setInterval(function() {
if (didScroll){
didScroll = false;
if(($(document).height()-$(window).height())-$(window).scrollTop() < 10){
pageCountUpdate();
}
}
}, 250);
//This function runs when user scrolls. It will call the new posts if the max_page isn't met and will fade in/fade out the end of page message
function pageCountUpdate(){
var page = parseInt($('#page').val());
var max_page = parseInt($('#max_page').val());
if(page < max_page){
$('#page').val(page+1);
getPosts();
$('#end_of_page').hide();
} else {
$('#end_of_page').fadeIn();
}
}
//Ajax call to get your new posts
function getPosts(){
$.ajax({
type: "POST",
url: "/load", // whatever your URL is
data: { page: page },
beforeSend: function(){ //This is your loading message ADD AN ID
$('#content').append("<div id='loading' class='center'>Loading news items...</div>");
},
complete: function(){ //remove the loading message
$('#loading').remove
},
success: function(html) { // success! YAY!! Add HTML to content container
$('#content').append(html);
}
});
} //end of getPosts function
There ya go! That's all. I was using Masonry with this code also so the animation worked wonderfully.
So I have an app, that allows you to add data, and then it displays all the data(still wip). So I made a Create and Read functionality so far using localStorage and jQueryMobile and jQueryUI.
But for some reason when I switch between pages(main page/add data page), I see cloned data on main page. Instead of 2 entries, I see 4 entries, and it's original 2 entries have a copy of each other. And when i refresh the page it's working fine, it displays only original data, without clones. Note that it's only happens when you go to Add page and then returning back to Main page(by clicking Home button).
Also When you are adding a run, for some reason it adding 2 runs at the same time(running add funciton 2 times)
Here is the code:
$(document).on('pageinit', function() {
//Display runs
showRuns();
//Add Handler for Adding Runs
$('#submitAdd').on('tap', addRun);
/*
* Show all runs on homepage
*/
function showRuns() {
//get runs Object
var runs = getRunsObject();
var i = 0;
if (runs != '' && runs != null) {
for (i; i < runs.length; i++) {
$('#stats').append('<li class="ui-body-inherit ui-li-static"><strong>Date: </strong>' + runs[i]["date"] + '<strong> <br/>Distnace: </strong>' + runs[i]["kms"] + 'km</li>');
}
$('#home').bind('pageinit', function() {
$('#stats').listview('refresh');
});
}
}
/*
* addRun function
*/
function addRun() {
//Get form values
var kms = $('#addKms').val();
var date = $('#addDate').val();
//Create 'Run' Object
var run = {
date: date,
kms: parseFloat(kms)
};
var runs = getRunsObject();
//Add run to runs array
runs.push(run);
alert('Run Added');
//Set stringified objects to localstorage
localStorage.setItem('runs', JSON.stringify(runs));
//Redirect
window.location.href = "index.php";
//Preventing form from submiting
return false;
}
/*
* getRunsObject
*/
function getRunsObject() {
//Set runs array
var runs = [];
//Get current runs from localStorage
var currentRuns = localStorage.getItem('runs');
//Check localStorage
if (currentRuns != null) {
//Set to runs
var runs = JSON.parse(currentRuns);
}
//Return sorted runs object
return runs.sort(function(a, b) {
return new Date(b.date) - new Date(a.date);
});
}
});
body {
text-align: center;
}
ul {
display: block;
}
.controls {
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Running Tracker</title>
<link rel="stylesheet" href="css/style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<!-- Main Page -->
<div data-role="page" id="home">
<header data-role="header" data-theme="a">
<h1>Running Tracker</h1>
</header>
<div data-role="navbar">
<ul>
<li>
Home
</li>
<li>
Add Run
</li>
</ul>
</div>
<div data-role="content">
<h3>Welcome to the RunningTracker App</h3>
<p>
With this app you can track your running, jogging or walking.
</p>
<h3>Your Latest Runs:</h3>
<ul id="stats" data-role="listview" data-filter="true" data-filter-placeholder="Filter runs by date or distance." data-inset="true"></ul>
<br/>
<button id="clearRuns" onclick="return confirm('Are You Sure?')">
Clear Data
</button>
</div>
<footer data-role="footer">
<h4>RunningTracker © 2015 GZ</h4>
</footer>
</div>
<!-- Add Run Page -->
<div data-role="page" id="add">
<header data-role="header" data-theme="a">
<h1>Running Tracker</h1>
</header>
<div data-role="navbar">
<ul>
<li>
Home
</li>
<li>
Add Run
</li>
</ul>
</div>
<div data-role="content">
<h3>Add Run</h3>
<form id="addForm">
<label for="km">Enter Kilometres:</label>
<input type="number" id="addKms">
<label for="km">Enter Date:</label>
<input type="date" data-role="date" class="date" id="addDate" data-inline="true">
<button id="submitAdd" class="ui-btn ui-corner-all">
Add Run
</button>
</form>
</div>
<footer data-role="footer">
<h4>RunningTracker © 2015 GZ</h4>
</footer>
</div>
</body>
</html>
For some reason example is not loading here on StackOverflow, so here is the live demo:
http://runningtracker.herokuapp.com/index.php
Try adding a new run, and then switch back to the add page, and then back to main page.
The problem is in the pageinit event handling. You are omitting the selector, so the handler is called twice (for home and for add pages), and in doing so you are calling $('#submitAdd').on('tap', addRun); twice, resulting in a double addRun call.
Change the line with:
$(document).on("pagecreate", "#home", function() {
(pagecreate now replaces pageinit, see jQM API)
Also, please change your "redirection" removing window.location.href = "index.php";.
That instruction changes the page bypassing jQuery Mobile navigation system, with the result of calling pageinit event after each addRun call (while it should be called only once).
Change your page using the change method instead:
$("body").pagecontainer("change", "#home", { transition: "none" });
Well, I found a solution. I replaced:
$(document).on('pageinit', function() {});
With:
$(document).one('pageinit', function() {});
As I understood it, I had 2 pages, so every function was running twice, and it was causing my problems. By using one instead of on I forced all the scripts to run only once, no matter how many pages I have.
I am having issues with an app I am creating. Depending on whether a variable of mine is null is supposed to show a specific screen. Once that variable has a value attached my app is supposed to display another div. However, my code is not working. Take a look at the Javascript/Jquery below:
(Note modifying the code in order to show that null is not the issue)
access_token = 3;
if (access_token == 3){
$('.dashboardProfile').hide();
$('.dashboardInfo').hide();
$('.dashboardConnect').show();
$('.connect').click(function () {
var url = "https://foursquare.com/oauth2/access_token";
url += "?client_id=" + foursquareApi.clientId;
url += "&response_type=token";
url += "&redirect_uri=" + foursquareApi.redirectUrl;
window.location = url;
});
}
else {
$('.dashboardProfile').show();
$('.dashboardInfo').show();
$('.dashboardConnect').hide();
}
and this is the HTML in question:
<div class="dashboard-container">
<div class="dashboardConnect">
<div class="connect">
<p>Sign In</p>
</div>
</div>
<div class="dashboardProfile">
<p>User Information and Picture</p>
</div>
<div class="dashboardInfo">
<p>Check Ins</p>
<div class="indicator checkin">#</div>
<p>Countries</p>
<div class="indicator country">#</div>
<p>Cities</p>
<div class="indicator city">#</div>
</div>
</div>
</div>
<!--container-fluid-->
This is the head of the HTML:
<head>
<title>FourSquare Dashboard</title>
<link rel="stylesheet" href="main.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="FourSquareJax.js"></script>
</head>
Easy fix. You made a small typo. Put $('.dashboardConnect').hide(); inside the else loop:
var access_token = 3;
if (access_token == 3) {
$('.dashboardProfile').hide();
$('.dashboardInfo').hide();
$('.dashboardConnect').show();
$('.connect').click(function() {
var url = "https://foursquare.com/oauth2/access_token";
url += "?client_id="+foursquareApi.clientId;
url += "&response_type=token";
url += "&redirect_uri="+foursquareApi.redirectUrl;
window.location = url;
});
}
else {
$('.dashboardProfile').show();
$('.dashboardInfo').show();
$('.dashboardConnect').hide();
}
Try changing your conditional to:
if (!access_token)
This will cause the conditional block to be entered if access_token is null, undefined, an empty string or 0.