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.
Related
I'm fairly new to javascript, and getting quite frustrated by the following code
<!DOCTYPE html>
<html>
<script>
var time = '0'
var area = 'neast'
function update_area(input) {
area = input;
load_updated_image(area,time);
};
function update_time(input) {
time = input;
load_updated_image(area,time);
};
function load_updated_image(area,time) {
var url = 'http://personal.psu.edu/kps5442/modelimages/hrrr_'+area+'_wetbulb'+time+'.png';
document.getElementById("theImage").src = url;
document.getElementById("url").innerHTML = url;
};
</script>
<body onload="load_updated_image(area,time)">
<p>URL Output:</p>
<p id="url"></p>
<font size = 4><b>Forecast Hour: </b>
<font size = 3>
<a href="#" onmouseover="update_time(0);" /> 00</a>
<a href="#" onmouseover="update_time(1);" /> 01</a>
<a href="#" onmouseover="update_time(2);" /> 02</a>
<img id="theImage" src=undefined width="850" height="600" />
<br> <font size = 4><b>Region Selection: </b>
<a href="#" onclick="update_area(neast);" /> Northeast</a>
<a href="#" onclick="update_area(seast);" /> Southeast</a>
</body>
</html>
I have 18 different "hours" of images for different regions across the US. The goal is to change the hour of the image when the hour links are moused over, and update the region when the region links are clicked.
The function update_time() works as expected, changing the image as I mouse over the links. However, the function update_area() fails with the following error:
"Uncaught ReferenceError: neast is not defined"
I'm not sure why this is happening, because the update_time and update_area functions are built in exactly the same way, and I globally defined the time and area variables at the start of the script.
Any help would be appreciated!
You have to put the arguments in quotes .
onclick="update_area('neast');"
onclick="update_area('seast');"
<!DOCTYPE html>
<html>
<script>
var time = '0'
var area = 'neast'
function update_area(input) {
area = input;
load_updated_image(area,time);
};
function update_time(input) {
time = input;
load_updated_image(area,time);
};
function load_updated_image(area,time) {
var url = 'http://personal.psu.edu/kps5442/modelimages/hrrr_'+area+'_wetbulb'+time+'.png';
document.getElementById("theImage").src = url;
document.getElementById("url").innerHTML = url;
};
</script>
<body onload="load_updated_image(area,time)">
<p>URL Output:</p>
<p id="url"></p>
<font size = 4><b>Forecast Hour: </b>
<font size = 3>
<a href="#" onmouseover="update_time(0);" /> 00</a>
<a href="#" onmouseover="update_time(1);" /> 01</a>
<a href="#" onmouseover="update_time(2);" /> 02</a>
<img id="theImage" src=undefined width="850" height="600" />
<br> <font size = 4><b>Region Selection: </b>
<a href="#" onclick="update_area('neast');" /> Northeast</a>
<a href="#" onclick="update_area('seast');" /> Southeast</a>
</body>
</html>
In JavaScript variables are not restricted to a single 'type', but a String will always be contained in quotes and a number will not. Also a variable cannot be, or start with, a number. This is why when you use a string as an argument it must be contained within quotes, otherwise it thinks you are sending a variable.
You're starting your document with <!doctype html> so you're saying you're writing HTML5, but there is a whole bunch of things that are incredibly wrong here due to use HTML3.2 and obsolete ways to invoke javascript.
Under modern HTML5 rules, there are no self-closing elements. It's not a hard error, but don't add that /> at the end of an <img.... Also <font> hasn't existed as element for 20 years now. It was removed in HTML4.1 in 1998. Then some semantics: if you need button functionality (i.e. clickable, but NOT navigating to some (part of a) page), use <button>. That's what it's for. Do not use <a>, and definitely not with href="#", because that's an active instruction for the browser to scroll to the top of the page. Finally, on...=... handlers are an ancient attribute that is unfortunately still supported, but you should never use. Use addEventListener in your Javascript, after you've declared all your HTML.
So let's just fix everything at the same time:
<!-- this line literally tells the browser "I am using HTML5" -->
<!DOCTYPE html>
<html>
<!-- always have a header section -->
<head>
<!-- no / at the end of meta elements -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Always just fill this in, it's good practice</title>
<style>
/* you want this in its own file, see the note at the end of this post */
h1 {
font-size: 100%;
font-weight: bold;
}
</style>
</head>
<body>
<!-- sectioning isn't mandatory, but extremely good practice -->
<section id="output">
<h1>URL Output:</h1>
<p>Forecast Hour:</p>
<div class="controls">
<!-- let's use data attributes, and be explicit about the values here -->
<button class="forecast update" data-value="0">0h</button>
<button class="forecast update" data-value="1">1h</button>
<button class="forecast update" data-value="2">2h</button>
</p>
<!-- if you've never see the figure/figcaption elements: they exist -->
<figure id="forecast-image">
<!-- no / at the end of this element -->
<img src="placeholder.jpg" width="850" height="600" alt="forecast map">
<figcaption></figcaption>
</figure>
</section>
<section>
<h1>Region Selection</h1>
<div class="controls">
<button class="area update" data-value="neast">Northeast</buton>
<button class="area update" data-value="seast">Southeast<button>
</div>
</section>
<!-- don't put your script in the page. put it in its own file -->
<script src="updates.js"></script>
</body>
</html>
And then we make a second file for the javascript called updates.js:
// this goes last, so that the DOM is done by the time you invoke your script.
var currentTime = 0;
var currentArea = `NorthEast`;
// this function doesn't need parameters: we already know what they are
function load_updated_image() {
var url = `http://personal.psu.edu/kps5442/modelimages/hrrr_${currentArea}_wetbulb${currentTime}.png`;
let figure = document.getElementById(`forecast-image`);
// update the image
let img = figure.querySelector(`img`);
img.src = url;
// update the image caption with a link
let caption = figure.querySelector(`figcaption`);
caption.innerHTML = ``;
let link = document.createElement(`a`);
link.href = url;
caption.appendChild(link);
}
// update the area, and called image update
function update_area(area) {
currentArea = area;
load_updated_image();
};
// update the time, and called image update
function update_time(time) {
currentTime = timel
load_updated_image();
};
// add the initial page load handling
document.addEventListener(`ready`, evt => load_updated_image());
// add the click handling for forecast time buttons
let forecastButtons = document.querySelectorAll(`button.forecastupdate`);
forecastButtons.forEach(button => {
// get the button's data-value
value = button.dataset.value;
// and then set up a click listener to update the forecast time
button.addEventListener(`click`, evt => update_time(value));
});
// add the click handling for forecast area buttons
let areaButtons = document.querySelectorAll(`button.area.update`);
forecastButtons.forEach(button => {
// get the button's data-value
value = button.dataset.value;
// and then set up a click listener to update the forecast area
button.addEventListener(`click`, evt => update_area(value));
});
And then to be even more proper, don't use <style>...</style> but make a new file called "forecast.css" and then link to that in your page using <link href="forecast.css" rel="stylresheet"> (note: this is still HTML5, you don't put /> at the end. Link elements simply don't have a closing tag)
For some reason, any event listener functions won't work on my browser(chrome), but they work on code pen? I been at this for about 2 hours, any thoughts?
Code pen link: http://codepen.io/koushkilla/pen/JXLVBX
<header>
<script src="pleasegodhelpme.js"></script>
<h1>Javascript Events</h1>
</header>
<main>
<h4>Add Numbers:</h4>
<p>
<input id="num-one"> + <input id="num-two">
</p>
<p id="add-sum"></p>
</main>
JS- FIle:
var numOne = document.getElementById("num-one");
var numTwo = document.getElementById("num-two");
var addSum = document.getElementById("add-sum");
numOne.addEventListener("input", add);
numTwo.addEventListener("input", add);
function add() {
var one = parseFloat(numOne.value) || 0;
var two = parseFloat(numTwo.value) || 0;
addSum.innerHTML = "your sum is: " + (one+two);
}
What happens is that your Javascript code is executed before the DOM has loaded. This means that you're making calls in the Javascript code to elements that don't exist yet.
The easiest way to solve this problem is to place your <script> tag just before the closing <body> tag. It's always good practice to place Javascript at the end of your page since it also increases loading times.
<body>
<header>
<h1>Javascript Events</h1>
</header>
<main>
<h4>Add Numbers:</h4>
<p>
<input id="num-one"> + <input id="num-two">
</p>
<p id="add-sum"></p>
</main>
<script src="pleasegodhelpme.js"></script>
</body>
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.
What I am trying to achieve is, to have a series of tables built up with PHP (the number of tables is dynamic) this is reloaded every 5 seconds by using setInterval. Then be able to click on one of the tables to show or hide it. Ive got most of this working, but I have gotten stuck on maintaining the state of the tables, be they visible or hidden. Every time the table reloads the table state resets as its returning to its original state (I think a new reference is being passed, actually im almost certain thats whats happening). I tried copying the reference to the divs to a variable and comparing it to an old one (I took that bit of code out as it wasnt working) but I couldnt get the old settings into the new tags.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var divStateArray;
function random_number() {
var random = Math.floor(Math.random()*110000);
return random;
}
//console.log(divStateArray);
function reload(state){
$(".responsecontainer").load('counter.php?randval=' + random_number(), function() {
var $rowelements = $(".divRow");
var $divRow = $('.divTable').find($rowelements);
//console.log($divRow);
//by copying $divRow it copies a reference/pointer into divStateArray.
//so any changes made to the properties of the div divRow are reflected in
//the afore mentioned variable.
divStateArray = $divRow;
//merge the old settings in divoldstate with the new references in divStateArray
if (state == 'all') {
divStateArray.hide();
}
});
}
//refresh the page every x miliseconds
var refreshId = setInterval(function() {
reload();
}, 5000);
$(document).ready(function() {
//show the spinning logo until the tables are loaded.
$(".responsecontainer").html('<img src="/lbadmin/images/ajax-loader.gif" width=32 height=32 />');
//display the page as soon as possible, then begin reloading every x seconds
reload('all');
$(document).on('click',".headRow",function(){
var $divRow = $(this).nextAll(".divRow")
//console.log($divRow);
if ($divRow.is(":hidden")) {
$divRow.show('fast');
}
else {
$divRow.hide('fast');
}
});
});
</script>
</head>
<body>
<p>hello</p>
<div class="responsecontainer" id="time1">
</div>
</br>
</body>
</html>
The table that gets loaded is (for the time being and for testing its just a static table but eventually this will change to multiple dynamic tables -
<?php
echo date("l, F d, Y h:i:s" ,time());
?>
<link rel="stylesheet" type="text/css" href="test.css" />
<p>hello</p>
</br>
<div class="divTable">
<div class="headRow">
<div class="divCell">LABEL: vippoo</div>
<div class="divCell">IP: 192.168.67.505</div>
<div class="divCell">Ports: 80-81</div>
<div class="divCell">Method: Layer 4</div>
<div class="divCell">Mode: DR</div>
<div class="divCell">Protocol: TCP</div>
<div class="divCell">Graph: link</div>
</div>
<div class="divRow">
<div class="divCell">label1</div>
<div class="divCell">192.168.66.666</div>
<div class="divCell">1</div>
<div class="divCell">Drain</div>
<div class="divCell">Halt</div>
<div class="divCell">uparrow</div>
<div class="divCell">graphlink</div>
</div>
<div class="divRow">
<div class="divCell">label1</div>
<div class="divCell">192.168.66.666</div>
<div class="divCell">1</div>
<div class="divCell">Drain</div>
<div class="divCell">Halt</div>
<div class="divCell">uparrow</div>
<div class="divCell">graphlink</div>
</div>
<div class="divRow">
<div class="divCell">label1</div>
<div class="divCell">192.168.66.666</div>
<div class="divCell">1</div>
<div class="divCell">Drain</div>
<div class="divCell">Halt</div>
<div class="divCell">uparrow</div>
<div class="divCell">graphlink</div>
</div>
</div>
</br>
Why don't you put a <div> around the table and show / hide that <div>? That way, if you reload the table, the visibility of the table remains the same as that is defined in the div around the table.
Why not simply check the state of the table before trying the refresh/reload?
If the table is hidden don't perform the refresh then the state of the table will not change.
Your set-interval method can continue to loop and that's where (within) you would add your check.
So your reload becomes something like this
function isTableHidden() {
var $divRow = $('.divTable').nextAll(".divRow")
return ($divRow.is(":hidden"))
}
function reload(state) {
if (isTableHidden())
return; // exit early and don't reload anything
$(".responsecontainer").load(
... rest of your oringal reload code ...
);
}
i got a page on a site and there are several videos within blocs. When i play one video and then hit the close button or click on another box to open it, it works all just fine. But the problem comes when i add extra html markup around the videos, it breaks the close button behavior.
Here's the markup of a box (i've got multiples in my page):
<div class="box" data-size="660,605">
<div class="cunload2">
<div class="expandable">
<span class="simple">
<a class="cunload" href="javascript:;"></a>
</span>
<div class="exandable-vids-container">
<iframe ... ></iframe>
</div>
</div>
</div>
</div>
The cunload button is the one closing the box and unloading the video.
Here's the javascript (as seing at the vimeo api's page):
(function(){
var vimeoPlayers = document.querySelectorAll('iframe'), player;
for (var i = 0, length = vimeoPlayers.length; i < length; i++) {
player = vimeoPlayers[i];
$f(player).addEvent('ready', ready);
}
function addEvent(element, eventName, callback) {
if (element.addEventListener) { element.addEventListener(eventName, callback, false); }
else { element.attachEvent(eventName, callback, false); }
}
function ready(player_id) {
var container = document.getElementById(player_id).parentNode.parentNode,
froogaloop = $f(player_id),
apiConsole = container.querySelector('.console .output');
function setupSimpleButtons() {
var unloadBtn = container.querySelector('.simple').querySelector('.cunload');
addEvent(unloadBtn, 'click', function() { froogaloop.api('unload'); }, false);
}
setupSimpleButtons();
$(".cunload, .box:not(.expanded)").click(function(){
//if (!$(this).is('expanded')) {
froogaloop.api('unload');
//}
});
}
})();
This works just fine, but when i add an extra <div> around the iframe (and i really need to) it doesnt work anymore.
Any clue?
EDIT: problem is more complicated, i added an <ul> and <li> tags around the iframes as such:
<div class="box" data-size="660,605">
<div class="cunload2">
<div class="expandable">
<span class="simple">
<a class="cunload" href="javascript:;"></a>
</span>
<div class="exandable-vids-container">
<ul>
<li><iframe ... ></iframe></li>
<li><iframe ... ></iframe></li>
</ul>
</div>
</div>
</div>
</div>
and modified the js line :
var container = document.getElementById(player_id).parentNode.parentNode
to:
var container = document.getElementById(player_id).parentNode.parentNode.parentNode.parentNode
and i got it working.
The problem is that i use the <ul> and <li> tags to call jcarousel and that it adds an extra 3 divs between my .exandable-vids-container and the <ul>. Moreover, sometimes i'll call this carousel and sometimes not, so i really can't go with adding extras .parentNode in the js. This would have to be dynamic and i think the solution has to be in that direction.