I am trying to run a function after a given DIV shows.
$(document).ready(function () {
$("#next").click(function () {
$("#nextwindow").show()
});
});
$(document).ready(function () {
$("#pagetitle-up").click(function () {
$.post('maindatabase.php', {
page: <? php echo $_GET[p]; ?> , sort: 1
},
function (data) {
var printthisline = "";
var data = $.parseJSON(data);
for (var i in data.results) {
printthisline += " <a href='main.php?p=" + data.results[i].id + "'> " + data.results[i].pagetitle + "</a>" + " | " + " <br> ";
}
document.getElementById("nexttable").innerHTML = printthisline;
});
});
});
When trying to bind them together so that the function only runs once the initial DIV shows, it stops working. Any suggestions why?
$(document).ready(function () {
$("#next").click(function () {
$("#nextwindow").show()
});
});
$(document).ready(function () {
$("#nextwindow").on('show', function () {
$.post('maindatabase.php', {
page: <? php echo $_GET[p]; ?> , sort: 1
},
function (data) {
var printthisline = "";
var data = $.parseJSON(data);
for (var i in data.results) {
printthisline += " <a href='main.php?p=" + data.results[i].id + "'> " + data.results[i].pagetitle + "</a>" + " | " + " <br> ";
}
document.getElementById("nexttable").innerHTML = printthisline;
});
});
});
Thank you
You could trigger manually your custom show event:
DEMO jsFiddle
$(document).ready(function () {
$("#next").click(function () {
$("#nextwindow").show().trigger('show');
});
});
Or use callback:
DEMO jsFiddle
$("#nextwindow").show(0,myCallback);
function myCallback(){
$.post(...);
}
That's said, why not call POST request on #nextwindow click???
Related
I'm working on a jquery mobile script to get json from my wordpress site but its not displaying anything and returns with a: 'Uncaught TypeError: Cannot read property 'length' of undefined' error. I know i'm messing up somewhere with parsing the json, but i happen to be a javascript noob. To the guy that both fixes and explains it to me, i thank you.
HTML:
ListView
<div data-role="page" id="home">
<div data-role="content">
<div class="example-wrapper" data-iscroll>
<ul data-role="listview" id="post-list" data-theme="a"></ul>
</div>
</div>
</div>
PageView
<div data-role="page" id="headline">
<div data-role="content">
<ul data-role="listview" id="post-data" data-theme="a"></ul>
</div>
</div>
JavaScript:
$(document).on('pageinit', '#home', function () {
$.ajax({
url: 'http://chris.floppytron.com/api/get_recent_posts/',
dataType: "jsonp",
success: function (result) {
ajax.parseJSONP(result);
},
error: function (request, error) {
alert('Network error has occurred please try again!');
}
});
});
$(document).on('pagebeforeshow', '#headline', function () {
$('#post-data').empty();
$.each(postInfo.result, function (i, row) {
if (row.id == postInfo.id) {
$('#post-data').append('<li>' + row.title + '</li>');
$('#post-data').append('<li>' + row.date + '</li>');
$('#post-data').append('<li>' + row.categories + '</li><br />');
$('#post-data').append('<li>' + row.content + '</li>');
$('#post-data').listview('refresh');
}
});
});
$(document).on('vclick', '#post-list li a', function () {
postInfo.id = $(this).attr('data-id');
$.mobile.changePage("#headline", {
transition: "slide",
changeHash: false
});
});
var postInfo = {
id: null,
result: null
}
var ajax = {
parseJSONP: function (result) {
postInfo.result = result.results;
$.each(result.results, function (i, row) {
console.log(JSON.stringify(row));
$('#post-list').append('<li><img src="' + row.thumbnail + '"/><h3>' + row.title + '</h3><p>' + row.categories + '</p><br /><p>' + row.date + '</p></li>');
});
$('#post-list').listview('refresh');
}
}
There is no function $.parseJSONP it's $.parseJSON without "P". Anyway, you don't need to parse the returned Ajax result since it is ready to be populated.
The returned array has no .results property, it is .posts.
postInfo.result = result.posts;
$.each(postInfo.result, function (i, row) {
Fixed code
$(document).on('pagecreate', '#home', function () {
$.ajax({
url: 'http://chris.floppytron.com/api/get_recent_posts/',
dataType: "jsonp",
success: function (result) {
addRows(result);
},
error: function (request, error) {
alert('Network error has occurred please try again!');
}
});
});
$(document).on('pagebeforeshow', '#headline', function () {
$('#post-data').empty();
$.each(postInfo.result, function (i, row) {
if (row.id == postInfo.id) {
$('#post-data').append('<li>' + row.title + '</li>');
$('#post-data').append('<li>' + row.date + '</li>');
$('#post-data').append('<li>' + row.categories + '</li><br />');
$('#post-data').append('<li>' + row.content + '</li>');
$('#post-data').listview('refresh');
}
});
});
$(document).on('click', '#post-list li a', function () {
postInfo.id = $(this).attr('data-id');
$.mobile.changePage("#headline", {
transition: "slide",
changeHash: false
});
});
var postInfo = {
id: null,
result: null
};
function addRows(result) {
postInfo.result = result.posts;
$.each(postInfo.result, function (i, row) {
$('#post-list').append('<li><img src="' + row.thumbnail + '"/><h3>' + row.title + '</h3><p>' + row.categories + '</p><br /><p>' + row.date + '</p></li>');
});
$('#post-list').listview('refresh');
};
Demo
Background
I have a modal that works when added as a script before the closing </body> as
<script>
// Simple modal
jQuery(function ($) {
// Load dialog on click
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
});
</script>
or if I have that function as its own .js file and call it that way.
Yes, I did clear my cache and verify in the Inspect Element to see if the script was being called.
Problem
When I put the function in my main javascript file in the app.js it, then the modal does not work.
Current Page
The test page is currently available at http://bruxzir.jgallardo.me/test.aspx
Code
This is the order in which I am calling my scripts from my <head>
<script src="/assets/js/jquery.js"></script>
<script src="/assets/js/mustache.js"></script>
<script src="/assets/js/headroom.min.js"></script>
<script src="/assets/js/jquery.simplemodal.js"></script>
<script src="/assets/js/swipe.js"></script>
<script src="/assets/js/app.js"></script>
<script src="/assets/js/google-analytics.js"></script>
HTML
<div id='basic-modal'>
<h3>Basic Modal Dialog</h3>
<input type='button' name='basic' value='Demo' class='basic'/>
</div>
<!-- modal content -->
<div id="basic-modal-content" class="featured-video">
<img src="http://placehold.it/720x360&text=Image+1">
<img src="http://placehold.it/720x360&text=Image+2">
</div>
app.js
/* Video Modal */
function overlay() {
el = document.getElementById("overlay");
el.style.display = (el.style.display == "block") ? "none" : "block";
}
/* Fixed Header */
$(window).scroll(function(){
if ($(window).scrollTop() >= 180) {
$('nav#page-menu').addClass('fixed-header');
}
else {
$('nav#page-menu').removeClass('fixed-header');
}
});
/* Main functionality for search of labs in the US */
$('#search').keyup(function () {
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('labs.js', function (data) {
console.log(data)
var output = '<ul class="searchresults">';
$.each(data, function (key, val) {
if ((val.abbr.search(myExp) != -1) ||
(val.state.search(myExp) != -1)) {
output += '<li>';
output += '<h5>' + val.name + '</h5>';
output += val.city + ', ' + val.abbr + ' ' + val.country + '<br />';
output += val.phone + '<br />';
output += '<a href="http://' + val.website + '"' + 'target="_blank"' + '>' + val.website + '</a>';
output += '</li>';
}
});
output += '</ul>';
$('#labs-container').html(output);
});
});
/* Passes data from JSON into international lab list */
$(function() {
$.getJSON('labs-international.js', function(data) {
var template = $('#labsCountryList').html();
var html = Mustache.to_html(template, data);
$('#countries').html(html);
});
});
/* Filter for international labs */
$('#lab-country-select').on('change', function (e) {
e.preventDefault();
var cat = $(this).val();
var nam = $(this).val();
$('#countries > div').hide();
$('#countries > div[data-category-type="'+cat+'"][data-category-name="'+nam+'"]').show();
});
/* Main functionality for search of international labs */
$('#search-intl').keyup(function () {
var searchField = $('#search-intl').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('labs-intl.js', function (data) {
console.log(data)
var output = '<ul class="searchresults">';
$.each(data, function (key, val) {
if ((val.country.search(myExp) != -1)) {
output += '<li>';
output += '<h5>' + val.name + '</h5>';
output += val.city + '<br />';
output += val.country + '<br />';
output += val.phone + '<br />';
output += '<a href="http://' + val.website + '"' + 'target="_blank"' + '>' + val.website + '</a>';
output += '</li>';
}
});
output += '</ul>';
$('#labs-container').html(output);
});
});
/* To hide the page navigation */
(function() {
new Headroom(document.querySelector("#page-menu"), {
tolerance: 5,
offset : 180,
classes: {
initial: "slide",
pinned: "slide--reset",
unpinned: "slide--up"
}
}).init();
}());
/* For mobile layout */
$("p").has("img").css({textAlign: "center"});
// Slider for Techincal Information - Polishing Kit
window.mySwipe = new Swipe(document.getElementById('slider'), {
startSlide: 0,
speed: 300,
auto: 600000,
continuous: true,
disableScroll: false,
stopPropagation: false,
callback: function(index, elem) {},
transitionEnd: function(index, elem) {}
});
// Slider for Techincal Information - Seating Instructions
// Add mySwipe2 here and in HTML control
window.mySwipe2 = new Swipe(document.getElementById('slider-2'), {
startSlide: 0,
speed: 300,
auto: 600000,
continuous: true,
disableScroll: false,
stopPropagation: false,
callback: function(index, elem) {},
transitionEnd: function(index, elem) {}
});
// Captions for slider in Technical Information
$(document).ready(function () {
var rm = $(".read-more");
var hi = $('.hide');
rm.click(function (e) {
e.preventDefault();
var now = $(".hide");
now.slideToggle();
hi.not(now).filter(':visible').slideToggle();
});
});
// Simple modal
jQuery(function ($) {
// Load dialog on click
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
});
My initial thoughts are that there might be a conflict in the app.js, so
Try this:
// Captions for slider in Technical Information
$(document).ready(function () {
var rm = $(".read-more");
var hi = $('.hide');
rm.click(function (e) {
e.preventDefault();
var now = $(".hide");
now.slideToggle();
hi.not(now).filter(':visible').slideToggle();
});
// Load dialog on click
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
});
Mentioned earlier on the comments that I might know the problem, didn't test this but see if this helps. I inserted the code into document.ready() function
I have the following JS/JQuery in the body of a my JQM (html) site, when I try to call sortMethod() I get 'ReferenceError: sortMethod is not defined' in FireBug console.
<script>
$(function(){
$("[name=radio-choice-h-3]").change(function() {
//alert('Selected: '+$('input[name=radio-choice-h-3]:checked').val());
sessionStorage.sortBy = $('input[name=radio-choice-h-3]:checked').val();
sortMethod();
});
});
$(function(){
sortMethod();
});
$(function sortMethod(){
if(sessionStorage.sortBy === "model" || sessionStorage.sortBy == null || sessionStorage.sortBy.trim())
{
theManufacturers('model');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2a", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === "year")
{
theManufacturers('year');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2b", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === "location")
{
theManufacturers('location');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2c", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === 'ttaf')
{
theManufacturers("ttaf");
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2d", page).prop("checked", true).checkboxradio("refresh");
});
}
});
$(function theManufacturers(inputSearch){
var qryString = 0;
//set up string for adding <li/>
var li = "";
var jqxhr = $.getJSON("url",
function(data){
$.each(data.items, function(i,item){
li+='<li><img src="' + item.Image.trim() + '" style="height:80px;/> <span style="font-size:0.75em;">' + item.Manufacturer.trim() + ' ' + item.Model.trim() + '(' + item.Price.trim() + ')</span><br/><span style="font-size:0.65em;">S/N: ' + item.Serial.trim() + ' | TTAF: ' + item.TTAF.trim() + ' | LOC: ' + item.Location.trim() + '</span><br/><span style="font-size:0.65em;">' + item.DealerName.trim() + '</span></li>';
});
$("#results-list").append(li);
$("#results-list").listview("refresh");
});
//jqxhr.done(function() {
// console.log( "second success" );
//});
});
What am I doing wrong?
<script>
//first you define your functions, they will not be executed "from alone"
//syntax:|function name() { .. code }
function sortMethod(){
if(sessionStorage.sortBy === "model" || sessionStorage.sortBy == null || sessionStorage.sortBy.trim())
{
theManufacturers('model');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2a", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === "year")
{
theManufacturers('year');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2b", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === "location")
{
theManufacturers('location');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2c", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === 'ttaf')
{
theManufacturers("ttaf");
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2d", page).prop("checked", true).checkboxradio("refresh");
});
}
};
//same here, just a defined function
function theManufacturers(inputSearch){
var qryString = 0;
var li = "";
var jqxhr = $.getJSON("url",
function(data){
$.each(data.items, function(i,item){
li+='<li><img src="' + item.Image.trim() + '" style="height:80px;/> <span style="font-size:0.75em;">' + item.Manufacturer.trim() + ' ' + item.Model.trim() + '(' + item.Price.trim() + ')</span><br/><span style="font-size:0.65em;">S/N: ' + item.Serial.trim() + ' | TTAF: ' + item.TTAF.trim() + ' | LOC: ' + item.Location.trim() + '</span><br/><span style="font-size:0.65em;">' + item.DealerName.trim() + '</span></li>';
});
$("#results-list").append(li);
$("#results-list").listview("refresh");
});
});
//here is an example how i outsourced your changehandler to a function
function initializeChangeHandler(){
$("[name=radio-choice-h-3]").change(function() {
//alert('Selected: '+$('input[name=radio-choice-h-3]:checked').val());
sessionStorage.sortBy = $('input[name=radio-choice-h-3]:checked').val();
});
};
//heres the function that will be executed when the document model is complete loaded
//syntax:|$(function(){ .. code .. })
$(function(){ // as the code inside here is executed, you can now call your functions
initializeChangeHandler();// <<-- example for understanding
sortMethod(); // <<-- heres the call
});
</script>
keep up to this structure ( initialize the stuff you defined before)
then you can be sure your functions are defined ;9
Move sortMethod in outer of scope $(), I mean sortMethod not need $()
function sortMethod(){
....
}
My js onclick event is not working for my portfolio. The page can be seen here: http://www.savantgenius.com/portfolio/branding and this is the script:
<script type="text/javascript">
$(function() {
var portDefault = 'bonya';
$('#portItem').hide();
$('#portLoader').fadeIn();
$('#portItem').load('http://www.savantgenius.com/portfolio/portfolio-item/' + portDefault + ' #portLoadedContent', function() {
$('#portLoader').fadeOut();
$('#portItem').fadeIn();
});
$('a.focusElement').focus();
});
function get_portfolio(portLocation) {
$('#portItem').fadeOut();
$('#portLoader').fadeIn();
$('#portItem').load('http://www.savantgenius.com/portfolio/portfolio-item/' + portLocation + ' #portLoadedContent', function() {
$('#portLoader').fadeOut();
$('#portItem').fadeIn();
});
}
The loading animation appears, but no image. Any thoughts are much appreciated, thanks!
Going off of #Christian Varga's comment, you need to return HTML with the source set as the link you create. Try something like:
$("#portItem").html($("<img>")
.attr("src", 'http://www.savantgenius.com/portfolio/portfolio-item/' + portLocation + '#portLoadedContent'));
instead of your .load() line.
So I guess your final function should be something like:
function get_portfolio(portLocation) {
$('#portItem').fadeOut();
$('#portLoader').fadeIn();
$("#portItem").html($("<img>")
.attr("src", 'http://www.savantgenius.com/portfolio/portfolio-item/' + portLocation + '#portLoadedContent'));
// UPDATE:
setTimeout(function () {
$('#portLoader').fadeOut();
$('#portItem').fadeIn();
}, 1000);
});
}
Check this solution:
HTML:
<div id="portItem"><img /></div>
JS:
$(function() {
var portDefault = 'bonya';
$('#portItem').hide();
$('#portLoader').fadeIn();
$('#portItem img').attr("src",'http://www.savantgenius.com/portfolio/portfolio-item/' + portDefault + '#portLoadedContent');
$('#portItem img').load(function() {
$('#portLoader').fadeOut();
$('#portItem').fadeIn();
});
});
function get_portfolio(portLocation) {
$('#portItem').hide();
$('#portLoader').fadeIn();
$('#portItem img').attr("src",'http://www.savantgenius.com/portfolio/portfolio-item/' + portLocation + '#portLoadedContent');
//check if image is loaded, then hide loader + show image:
$('#portItem img').load(function() {
$('#portLoader').fadeOut();
$('#portItem').fadeIn();
});
}
See demo : http://jsfiddle.net/esqmr/1/
Try removing the space before #portLoadedContent
<script type="text/javascript">
$(function() {
var portDefault = 'bonya';
$('#portItem').hide();
$('#portLoader').fadeIn();
$('#portItem').load('http://www.savantgenius.com/portfolio/portfolio-item/' + portDefault + '#portLoadedContent', function() {
$('#portLoader').fadeOut();
$('#portItem').fadeIn();
});
$('a.focusElement').focus();
});
function get_portfolio(portLocation) {
$('#portItem').fadeOut();
$('#portLoader').fadeIn();
$('#portItem').load('http://www.savantgenius.com/portfolio/portfolio-item/' + portLocation + '#portLoadedContent', function() {
$('#portLoader').fadeOut();
$('#portItem').fadeIn();
});
}
Buildgames returns rows:
<a>....</a>
<a>....</a>
When I click on each a the Buildcar_s function returns all the data inside an alert.
Instead of this alert I want to put all the results in a div under each a, so it would look like:
<a>.....clicked ...</a>
<div>....
...
</div>
<a>....not clicked...</a>
<a>....not clicked...</a>
<a>....not clicked...</a>
How can we put a div only under the a which was clicked?
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += 'mmmmmm<br/>';
});
place += '</div>';
return place;
}
Try this, relevant changes have been commented:
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
var $a = this;
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
// this inserts the HTML generated from the function,
// under the A element which was clicked on.
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += '<div style="float: right;"> ' + this.CITY + ' ' + '</div><BR />' + +'<br/><br/>';
});
place += '</div>';
return place; // returns the string created, as opposed to alerting it.
}