Well I´ve been breaking my head with this problem for some time, I´ve tried tons of solutions online yet none of them work.
What I need is to feed data from a json to a listview on page load and present it yet it only works on index after that I need to reload every page so I can see the listview.
Here´s my jquery code:
$(document).bind("mobileinit", function () {
$.mobile.ajaxEnabled = false;
});
$(document).bind('pageinit',function() {
DrawPageContent();
});
function DrawPageContent() {
$.ajax({
dataType: "json",
url: "js/categorias.json",
success: function(msg){
console.log(msg.categorias[1].nombre);
var categos = '';
for(var i=0;i<msg.categorias.length;i++){
categos += '<li><a href="refrescos.html?id='+ 0 +'"><img src="'
+ msg.categorias[i].logo + '"><h2>'+msg.categorias[i].nombre
+ '</h2><p>' + msg.categorias[i].desc + '</p></a></li> ';
}
$("#categorias").html(categos);
$("#categorias").listview("refresh");
//$("#page").trigger("pagecreate");
}
});}
I've also tried $(document).ready() and some other things.
Here's the HTML for that part:
<div id="page" data-role="page">
<div data-role="header">
<h1>Categorias</h1>
Opciones
</div>
<div data-role="content">
<ul id="categorias" data-role="listview" data-inset="true">
</ul>
Any ideas how to fix this?
If you are trying to append to the id "categorias" each time that is why it only appends to the first page.
In JQuery mobile the pages that are loaded aren't actually removed from the DOM right away. That means that if you load more than one page that has the and element with id categorias in it, it will end up with multiple DOM elements with categorias identifying them. In this case, it will only append to the first one, which would explain why it is not showing up on your other pages until you refresh and the other pages are removed from the DOM.
A good solution here is to give each page a unique identifier and then select the categorias from that page using
$("#categorias", "#pageidentifier");
This selector will search within the specific page you specify to find your categorias element.
Related
I'm opening this question because of the problem that came out from a previous one: Dynamically update HTML images from Flask+Ajax.
Reassuming, I needed to update my HTML view after a response obtained thanks to AJAX from a Flask entrypoint.
HTML
<ul>
{% for image in list%}
<li>
<img src="{{image}}" height="150" width="150"></img>
</li>
{% endfor %}
</ul>
AJAX function
$.ajax({
url: "/...",
type: "POST",
dataType: 'json',
data: {...},
success: function(resp){
$("ul").children().remove();
for (var i = 0; i < resp.length; i++) {
var elem = "<li><img src=" + resp[i] + "></li>";
$("ul").append(elem);
}
}
});
The problem is that after I update the view, following the same structure as the "original" HTML, all of the CSS linked to the images combined with Jquery effects ( tag) doesn't work anymore (like hover effects, ecc.).
Does anyone have suggestions, or maybe suggest another working way to accomplish the task?
I think this answer may help with your problem, take a look: https://stackoverflow.com/a/17715303/11388121.
In practice, that's because the HTML you injected after the AJAX function isn't the "original" one that was executed at page loading.
Thus, you may need some event delegation.
I have the following HTML5 and Java Script code.
PROBLEM: This code will not display the first video clip at index 0.
The code plays all the remaining video clips (from index 1 on-wards) as normal.
The code is available live at
http://mvl.ecs.soton.ac.uk:8080/JustPlayList.jsp
This code will obviously run in HTML5 enabled browsers.
Any help about how to play the first video clip will be really appreciated.
Many thanks,
<div id="VideoContainer"></div>
<div id="num"></div> <script>
var URLArray = new Array();
URLArray[0] = "/VideoContents/AtomVideo/AtomPart1/AtomPart1C.mp4";
URLArray[1] = "/VideoContents/AtomVideo/AtomPart2/AtomPart2C.mp4";
URLArray[2] = "/VideoContents/AtomVideo/AtomPart4/AtomPart4C.mp4";
URLArray[3] = "/VideoContents/AtomVideo/AtomPart5/AtomPart5C.mp4";
URLArray[4] = "/VideoContents/AtomVideo/AtomPart6/AtomPart6C.mp4";
URLArray[5] = "/VideoContents/AtomVideo/AtomPart7/AtomPart7C.mp4";
</script>
<script>
$(document).ready(function()
{
NextFrag();
});
var index=0;
function NextFrag(){
if (index < URLArray.length)
{
alert("Index Value is :" + index);
$("#VideoContainer").html('<video id="video1" controls autoplay > "<source src= "'+ URLArray[index]+ '" type="video/mp4"></source> </video>' );
$("#num").html('Displaying Part : ' +(index+1) + ' ' );
index++;
$("#video1").bind( "ended", NextFrag);
}
}
</script>
There does not appear to be anything wrong with your code, but I think you are getting a weird interaction with jQuery mobile. So the fix seems to be the following. Wrap your HTML in a <div data-role="page"> to tell jQM that this is a mobile page and then put the code in pageinit instead of document.ready. Here is a working demo: http://jsfiddle.net/ezanker/Ep52A/
<div data-role="page">
<div data-role="content">
<center>
<h1>Test Page</h1><h3>Test Page</h3><br /><br />
<div id="VideoContainer"></div>
<div id="num"></div>
<button>Go to Previous Part</button>
<button>Go to Next Part</button>
</center>
</div>
</div>
Here is the code that calls nextFrag:
var index = 0;
$(document).on("pageinit", function(){
NextFrag();
});
UPDATE: jQM Doc explains the problem: http://view.jquerymobile.com/1.3.2/dist/demos/widgets/pages/
Also Note: If your body contains no data-role="page" divs, jQuery Mobile wraps the entire contents of the body within a page div as explained above. jQuery Mobile is using jQuery's wrapAll() method to do this which looks for any script tags inside the content being wrapped, and loads each script source via XHR. If scripts are present in the body, the browser ends up loading them twice. We therefore strongly recommend that jQuery Mobile documents with scripts in their body also contain a div with data-role="page".
So your script in the page was being loaded twice upon initialization calling NextFrag twice and ending up on the second fragment instead of the first.
I Have Been working on a page the using a jquery autocomplete so that while your typing in a clients name its searching the databases for any macth containing that phrase. so using "LIKE" .
i have also put together a jquery silder so that it displays the records that are automaticly loaded from the database and when u click on one it will load more inofmation from the database..
indivaully thesse 2 pieces of code work fine so the jquery autocomplete on a serprate page just loading text enterys from a database.
and the jquery slider works fine with manually entered data and data loaded by php from a database..
but when i put them together the problem is it shows the record on the screen with the styling from the jquery slider but when u click the record it doesnt show anything so no slider (atm just manual html data in the slider for testing)
i have tried multipule tests such as running them serpeatre, placing them in different div tags. i have got it to work with a single sql query but it isnt what i need to do because i dont want the page to need to be refreshed for loading data.
i have placed my code from both files so th is first one is what calls the ajax request to create the records..
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".recordrow").click(function() {
var divid = "details-" + $(this).attr('id').split("-")[1]; //Create the id of the div
$("#"+divid).show().animate({ "right": '0%'}); //Bring the div from right to left with 200px padding from the screen
});
$('#bt-close').click(function(){
$('.details').animate({right:-2000}, 500);
});
});
function getStates(value){
$.post("sql.php",{partialState:value},function(data){
$("#results").html(data);
});
}
</script>
<input type="text" onkeyup="getStates(this.value)"/>
<br />
<div id="results">
</div>
And this is the page which querys the database
<?php
if($_POST['partialState']){
mysql_connect("localhost","root")or die (mysql_error());
mysql_select_db("ict_devices") or die (mysql_error());
$test=$_POST['partialState'];
$text="... More details of the records";
$states = mysql_query("Select * from students Where FirstName LIKE '%$test%'");
while($state= mysql_fetch_array($states)){
echo '<div class="recordrow" id="row-$state["id"]">'.$state['FirstName'].'</div>';
echo '<div class="details" id="details-$state["id"]">'.$text.'Close</div>';
}
}
?>
any help would be greatly appricated
I think you need to bind a click function on "recordrow" div after you got it by ajax. In your code there are no "recordrows" on the moment a click event binds. So you need something like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function getStates(value){
$.post("sql.php", function(data){
$("#results").html(data);
$('.recordrow').each(function() {
$(this).bind('click', function() {
var divid = "details-" + $(this).attr('id').split("-")[1]; //Create the id of the div
$("#"+divid).show().animate({ "right": '0%'}); //Bring the div from right to left with 200px padding from the screen
});
});
$('#bt-close').each(function() {
$(this).bind('click', function(){
$('.details').animate({right:-2000}, 500);
});
});
});
}
</script>
Your ajax is right and when you test slider recordrows already in DOM, click binds correcly. That is why it works by parts
EDIT: I test my code and add binding of bt-close event, it works for me, try it. It shows details when clicked and animation launches
I'm currently in the process of redoing a website and all of my pages are going to have a common navigation bar at the top:
Little snippet of the code I'm talking about:
<div id="logoNavContainer">
<nav>
<ul>
<li>Services</li>
<li>Products</li>
<li>Training</li>
<li>Technology</li>
<li>Clients</li>
<li>Publications</li>
<li>Contact Us</li>
</ul>
</nav>
</div>
Initially when I was coding this I was (and still am if it is possible) thinking it would be really convenient if I could have my mainTemplate.html for each page and then for their individual content, create a separate .html page that would be displayed within the correct area on the mainTemplate.
That way any changes to the navBar, links, background etc. Could be done from one location, which is something that I feel might exist due to the purpose of CSS.
But, as it is I simply have identical HTML code at the start of each page for the navbar but at least it is all styled by one CSS form.
So I (and future programmers) can edit the style for all pages from one spot.
Now that I'm implementing each page I am noticing that I have to go through increasingly more pages to change the navBar links, and it is the same action each time.
I was wondering if it is possible to set a variable or something in each html file (like in Java) which is set in one location so that all the links can be swapped out at once?
I'm just trying to make changes easier, and eliminate redundancy. I'm quite new to Html and CSS so I feel like I could be missing a very obvious solution.
Also if the original idea I had IS possible, I would much prefer this solution as it solves more than one problem, and eliminates scores of redundant code.
Thanks in advance.
In pure HTML that's not possible. There are two possible solutions that I can think of right now:
Preprocessing
You can serve your static HTML page using any processor like PHP. This is the best approach in my opinion. It will only require you to call include('header.html') and the header will be included. This is how it's done everywhere.
JavaScript
You can also load the navbar from a different location using JavaScript. The downside here is that it will requiere two requests per page and you'll have to put up some kind of loading animation until the navbar is loaded.
EDIT: I just realized you can use frames/iframes in pure HTML. Bear in mind I didn't come up with frames in the first place because... well, frames suck :)
You can see this article. Pure HTML does not support includes. The article includes a JavaScript solution you can use (see below for an excerpt).
So for your code, you could do:
var navigationDiv = "<div id='logoNavContainer'>" +
"<nav>" +
"<ul>" +
"<li><a href='contentPage.html' class='glow'>Services</a></li>" +
"<li><a href='contentPage.html' class='glow'>Products</a></li>" +
"<li><a href='contentPage.html' class='glow'>Training</a></li>" +
"<li><a href='contentPage.html' class='glow'>Technology</a></li>" +
"<li><a href='contentPage.html' class='glow'>Clients</a></li>" +
"<li><a href='publications.html' class='glow'>Publications</a></li>" +
"<li><a href='contentPage.html' class='glow'>Contact Us</a></li>" +
"</ul>" +
"</nav>" +
"</div>";
document.write(navigationDiv);
The very dirty solution:
Create mymenu.js with the content:
document.write("<div id='logoNavContainer'><nav><ul><li><a href='contentPage.html' class='glow'>Services</a></li></ul></nav></div>");
In all html you want to give navbar include this:
<script src="mymenu.js"></script>
Hope it helps!
Peter
Okay, I worked at this for a while; researching each of your answers and trying to work it into my code.
The PHP I am completely unfamiliar with, so I didn't get anywhere playing with it and although I worked with javascript I gave up on that as well.
Until I came back and saw Rachel G's updated answer. I used that combined with a discussion on generating html with javascript along with my own piece of javascript I managed to work out a functioning version of exactly what I wanted!
Here is how the HTML that I now include at the beginning of every page:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="styleSheet.css" rel="styleSheet" />
<script src="pageFeatures.js" type="text/javascript"></script>
</head>
<body onload="init('tabs')">
<div id="main-container">
<div id="navBar">
<!-- Loaded through Javascript; eliminates repeated code and all navBar Links are now set in one place -->
</div>
.... All page specific code.
And the javascript that creates the navBar:
The Links:
// Links
var servicesPage = 'designAudit.html';
var productsPage = 'pageTemplate.html';
var trainingPage = 'pageTemplate.html';
var technologyPage = 'pageTemplate.html';
var clientsPage = 'pageTemplate.html';
var publicationsPage = 'publications.html';
var contactPage = 'pageTemplate.html';
The Init()
function init(tabs) {
initNavBar();
if (tabs == 'tabs') {
initTabs();
}
}
InitNavBar()
// BEGIN NAVBAR GENERATING CODE
function initNavBar() {
var navBar = document.getElementById("navBar");
var navContainer = document.createElement("div");
navContainer.setAttribute('id','logoNavContainer');
var header = document.createElement("header");
var h1 = document.createElement("h1");
var logo = document.createElement("a");
logo.setAttribute('href','index.html');
h1.appendChild(logo);
var nav = document.createElement("nav");
var ul = document.createElement("ul");
var link1 = createLink(servicesPage, "Services");
var link2 = createLink(productsPage, "Products");
var link3 = createLink(trainingPage, "Training");
var link4 = createLink(technologyPage, "Technology");
var link5 = createLink(clientsPage, "Clients");
var link6 = createLink(publicationsPage, "Publications");
var link7 = createLink(contactPage, "Contact");
ul.appendChild(link1);
ul.appendChild(link2);
ul.appendChild(link3);
ul.appendChild(link4);
ul.appendChild(link5);
ul.appendChild(link6);
ul.appendChild(link7);
nav.appendChild(ul);
header.appendChild(h1);
header.appendChild(nav);
navContainer.appendChild(header);
navBar.appendChild(navContainer);
}
createLink()
// Indented to Represent Html layering.
function createLink(destPage, text) {
var link = document.createElement("li"); // <li>
var linkAnchor = document.createElement("a"); // <a>
linkAnchor.setAttribute('href', destPage); // <a href="">
linkAnchor.setAttribute('class','glow'); // <a href="" class="glow">
var services = document.createTextNode(text); // <a href="" class="glow">Text
linkAnchor.appendChild(services); // </a>
link.appendChild(linkAnchor); // <li>
return link;
}
Anyways, thanks for the assistance. I thought I would post the solution I came up with as it differs quite significantly from what's here.
One question I do have though, if anyone checks over this, is This completely leaves my site to die an aesthetic if the client's browser doesn't have it. Is this something that is likely to happen?
I know I have never personally used a computer without javascript but the world usually isn't that simple.
I'll try to explain:
I have numerous div classes, but for the sake of simplicity, let's say I only have 3.
Someone is viewing DIV 1, and I want to give them the option of only printing DIV 1, omitting 2 and 3.
However, on the same page, I would like to give them the option to ONLY PRINT DIV 2. Or only print DIV 3.
I think I get how you can omit certain things from getting printed. But how can you select a section here or there on the same page to be printed with a print link.
Thanks,
Tracy
You can use jQuery to show/hide divs. Read the jQuery tutorial:
http://docs.jquery.com/Tutorials
The code will look this way:
<script>
function showDiv(n) {
$('.divs').hide();
$('#div_'+n).show();
}
$(document).ready(function() { showDiv(1); });
</script>
<a href='javascript:showDiv(n)'>show div n</a>
<div class='divs' id='div_n'>I'm div n</div>
There are many related posts on printing div content, this particular question was still open though it was asked in '10.. Following JavaScript function can be used for printing content of a selected Div tag. Hope this helps. Declaimer: I used some of the existing answers, fixed/enhanced code/error(s) to work with (and tested on) IE-8.
function printDiv(divName) {
var divToPrint = document.getElementById(divName);
var newWin = window.open('', 'PrintWindow', 'width=400, height=400, top=100, left=100', '');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</body></html>');
newWin.document.close();
setTimeout(function () { newWin.close(); }, 10);
}
Call printDiv from anywhere in page or from within selected Div. Here is test link:
Print Customer Data
Print Order Data
Assign respective IDs to Div that is to be printed:
<div id="divCustomerData">Div Contents goes here... </div>
The only catch right now is it loses css styles. I'll update response when i get a chance to fix it. Thanks.
https://github.com/jasonday/jquery.printThis
I would give each div an id, and then using the above plugin (i wrote) specify according to div id.