Preloading images for cycle BEFORE hiding specific DIV and updating url - javascript

I have a project where I want to show a specific div (about the company) while a large fullscreen jQuery cycle is loading. I don't want to show the loading div until the images are loaded. It works well locally, but when I upload it the page shows the about div (#index-about) long enough for the first image to load. If you use the cycle to move to the next slide the next image is not loaded yet. I deduced that it must not be preloading correctly.
Here's my code. Thanks in advance! *EDIT: per request, here's everything. Warning: it's a ton of code. *
THE HTML:
<!doctype html>
<!--[if lt IE 7 ]> <html class="no-js ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]> <html class="no-js ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]> <html class="no-js ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>SGC</title>
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport">
<link rel="shortcut icon" href="/favicon.ico">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="stylesheet" href="css/style.css?v=2">
<!-- Lightbox CSS -->
<script src="js/libs/modernizr-1.7.min.js"></script>
<!-- scripts concatenated and minified via ant build script-->
<script src="js/libs/jquery-1.6.2.min.js"></script>
<script src="js/libs/jquery.cycle.all.js"></script>
<script src="js/libs/jquery.mousewheel.min.js"></script>
<script src="js/libs/jquery.easing.1.3.js"></script>
<script src="js/libs/jquery.address-1.4.min.js"></script>
<script src="js/libs/jquery.waitforimages.js"></script>
<script src="js/index2.js"></script>
<script src="js/ajax.js"></script>
</head>
<body>
<div id="container">
<h1><img src="images/SGC_logotype.png" alt="SGC"></h1>
<header>
<div id="nav-pulldown">
</div>
<div class="loading"></div>
<div id="overlay_b1"></div>
<div id="overlay_b2"></div>
<div class="overlay" id="overlay-main">
<ul id="nav-main" style="opacity:0;">
<li></li>
<li></li>
<li></li>
</ul>
</div>
</header>
<div id="main" role="main">
<div id="loading_page" style="display:none; "><img src="images/ajax-loader-gray.gif"/></div>
<div id="main-content">
</div><!-- eo main-content-->
<!-- ABOUT -->
<div class="overlay" id="index-about">
<div id="about-slider-container">
<ul class="about-slider">
<li class="about-statement" id="statement-1">
<h2>What if the medium isn't the entire message?</h2>
<p class="grey quote">"It's ideas that connect with consumers, build brands, and unleash the full potential of communications, both online and off."<br>
<span style="float:right;margin-right:20px;"> — SGC</span></p>
</li>
<!-- eo statement-1-->
</ul>
</div><!-- eo about-slider-container-->
</div>
<!-- / ABOUT -->
</div>
<footer>
</footer>
</div> <!-- eo #container -->
<!--<script>
$('#loading_page').css('margin-top',($(window).height()-64)/2);
</script>-->
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<script>window.jQuery || document.write("<script src='js/libs/jquery-1.6.2.min'>\x3C/script>")</script>
-->
<!-- end scripts-->
<!--[if lt IE 7 ]>
<script src="js/libs/dd_belatedpng.js"></script>
<script>DD_belatedPNG.fix("img, .png_bg");</script>
<![endif]-->
<!-- Google Analytics
<script>
var _gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]]; // Change UA-XXXXX-X to be your site's ID
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js";
s.parentNode.insertBefore(g,s)}(document,"script"));
</script> -->
</body>
</html>
THE JS:
function ClickURLHash(o,i){
var urlHash = o.attr("id");
$.address.value(urlHash);
}
function LoadURLHash(){
var urlHash = location.hash;
urlHash = urlHash.replace(/^#\//,"");
var myHref = $(this).attr('href');
if ((urlHash == "") || (urlHash == "index")){
if ($('#topbluelink').hasClass('active')){ //DROPDOWN ON
$('#overlay-main').animate({top:'100%'},600,'easeOutQuint');
$("#overlay_b2").delay(300).animate({top:'100%'},600,'easeInOutQuint');
$("#overlay_b1").delay(600).animate({top:'100%'},600,'easeInOutQuint',function(){
$('#main-content').fadeTo(600,0,function(){
$('#main-content').load('pages/home.html').animate({opacity:'1'},600),function(){
$.address.value("/");
};
});
$('#topbluelink').removeClass('active');
});
}
else if (!$('#topbluelink').hasClass('active')){ //DROPDOWN OFF
$('#overlay_b2,#overlay_b1').css('top','100%');
$('#overlay-main').animate({top:'100%'},600,'easeOutQuint',function(){
$('#main-content').fadeTo(600,0,function(){
$('#main-content').load('pages/home.html').animate({opacity:'1'},600),function(){
$.address.value("/");
};
});
$('#topbluelink').removeClass('active');
});
}else{
//new code
//$('#loading_page').html('<img src="images/ajax-loader-black.gif"/>').css('display','');
//$('#index-about').show();
var _images = ["images/index/gshock_collage.jpg", "images/index/tryx_collage.jpg", "images/index/mb_collage.jpg", "images/index/lapp_collage.jpg", "images/index/ciroc_collage.jpg", "images/index/empress_collage.jpg", "images/index/wwglass_collage.jpg","images/backgrounds/bg_trans-black90.png","images/nav/nav_gshock-sprite.png","images/nav/nav_pilkingtonplanar-sprite.png"];
var gotime = _images.length;
$.each(_images,function(e) {
$(new Image()).load(function() {
if (--gotime < 1)
{
$('#index-about').fadeOut(300, function(){
$('#loading_page').css('display','none').html('<img src="images/ajax-loader-gray.gif"/>');
$('#main-content').css('opacity','0').load('pages/home.html',function(){
$('#main-content').animate({opacity:'1'},400);
});
});
}
}).attr('src',this);
});
$('#topbluelink').removeClass('active');
$.address.value("/");
}
} else if ((urlHash == "work") || (urlHash == "contact")) {
if ($('#topbluelink').hasClass('active')){
$('#overlay-main').stop().animate({top:'100%'},600,'easeInOutQuint');
$("#overlay_b2").delay(300).animate({top:'100%'},600,'easeInOutQuint');
$("#overlay_b1").delay(600).animate({top:'100%'},600,'easeInOutQuint');
$('#main-content').load('pages/'+urlHash+'.html').css('top','100%')
.animate({top:'0%',opacity:'1'},600,'easeOutQuint',function(){
$('.overlay').children().animate({opacity:'1'},1000,'easeOutQuint');
$.address.value("/"+urlHash);
$('#topbluelink').removeClass('active')
});
}
else{
//new cod2e
$('#overlay-main').stop().animate({top:'100%'},600,'easeOutQuint');//change top from -100%
$("#overlay_b2").delay(300).animate({top:'100%'},600,'easeInOutQuint');
$("#overlay_b1").delay(600).animate({top:'100%'},600,'easeInOutQuint');
$('#main-content').delay(600).load('pages/'+urlHash+'.html').css('top','0%')
.animate({top:'0%',opacity:'1'},600,'easeOutQuint',
function (){
$('.overlay').children().animate({opacity:'1'},1000,'easeOutQuint');
});
$.address.value("/"+urlHash);
$('#topbluelink').removeClass('active');
}
$('ul#nav-work').animate({opacity:'1'},600,'linear');
$('.overlay').children().animate({opacity:'1'},1000,'easeOutQuint');
//KILL INDEX ABOUT
var _images = ["images/index/gshock_collage.jpg", "images/index/tryx_collage.jpg", "images/index/mb_collage.jpg", "images/index/lapp_collage.jpg", "images/index/ciroc_collage.jpg", "images/index/empress_collage.jpg", "images/index/wwglass_collage.jpg","images/backgrounds/bg_trans-black90.png","images/nav/nav_gshock-sprite.png","images/nav/nav_pilkingtonplanar-sprite.png"];
var gotime = _images.length;
$.each(_images,function(e) {
$(new Image()).load(function() {
if (--gotime < 1)
{
$('.overlay#index-about').css('display','none').hide().remove()
$('#loading_page').css('display','none').html('<img src="images/ajax-loader-gray.gif"/>');
$('#main-content').css('opacity','0').load('pages/'+urlHash+'.html',function(){
$('#main-content').animate({opacity:'1'},400);
});
}
}).attr('src',this);
});
} else if (urlHash == "about"){
if ($('#topbluelink').hasClass('active')){
$('#overlay-main').stop().animate({top:'100%'},600,'easeInOutQuint');
$("#overlay_b2").delay(300).animate({top:'100%'},600,'easeInOutQuint');
$("#overlay_b1").delay(600).animate({top:'100%'},600,'easeInOutQuint');
$('#main-content').load('pages/'+urlHash+'.html').css('top','100%')
.animate({top:'0%',opacity:'1'},600,'easeOutQuint',function(){
$('.overlay').children().animate({opacity:'1'},1000,'easeOutQuint');
$.address.value("/"+urlHash);
$('#topbluelink').removeClass('active')
});
}
else{
//new cod2e
$('#index-about').hide();
$('#overlay-main').stop().animate({top:'100%'},600,'easeOutQuint');//change top from -100%
$("#overlay_b2").delay(300).animate({top:'100%'},600,'easeInOutQuint');
$("#overlay_b1").delay(600).animate({top:'100%'},600,'easeInOutQuint');
$('#main-content').delay(600).load('pages/'+urlHash+'.html').css('top','0%')
.animate({top:'0%',opacity:'1'},600,'easeOutQuint',
function (){
$('.overlay').children().animate({opacity:'1'},1000,'easeOutQuint');
});
$.address.value("/"+urlHash);
$('#topbluelink').removeClass('active');
}
$('ul#nav-work').animate({opacity:'1'},600,'linear');
$('.overlay').children().animate({opacity:'1'},1000,'easeOutQuint');
} else {
if ($('#topbluelink').hasClass('active')){
$('#overlay-main').animate({top:'-100%'},600,function(){
$("#overlay_b2").delay(200).animate({top:'-100%'},600,'easeInOutQuint');
$("#overlay_b1").delay(400).animate({top:'-100%'},600,'easeInOutQuint');
$('#main-content').load('pages/'+urlHash+'.html').css('top','100%')
.animate({top:'0%'},600,'easeOutQuint'),function(){$.address.value("/"+urlHash)};
});
$('.overlay').children().animate({opacity:'1'},1000,'easeOutQuint');
$('#topbluelink').removeClass('active');
}
else{
//IF THIS IS A PROJECT PAGE (not #/about, #/work, or #/contact)
$('#index-about').hide();
$("#overlay_b1").animate({top:'0%'},600,'easeInOutQuint');
$("#overlay_b2").delay(400).animate({top:'0%'},600,'easeInOutQuint');
$('#main-content').delay(800).animate({top:'0%'},600,'easeOutQuint', function (){
$('#loading_page').css('display','block');
$('#main-content').load('pages/'+urlHash+'.html', function () {
$('#main-content').waitForImages(function()
{
$('#loading_page').css('display','none');
$("#overlay_b2").animate({top:'100%'},600,'easeInOutQuint');
$("#overlay_b1").delay(400).animate({top:'100%'},600,'easeInOutQuint');
$('#main-content').delay(800).show(600).css('top','-100%').animate({top:'0%'},600,'easeOutQuint',
function (){
slide_top = ($('.detail-slide-content').css('height').replace('px','')-$('.detail-slide-body').css('height').replace('px',''))/2+200;
$(".detail-slide-body").css('top', slide_top+'px');
$('.detail-slide-content').animate({opacity:'1'},1000,'easeOutQuint');
}
//
);
});
});
});
$.address.value("/"+urlHash);
$('#topbluelink').removeClass('active');
}
}
}
$(document).ready(function(){
$.address.externalChange(function(event) {
LoadURLHash();
});
});
$(window).load(function(){
$('#main-content').animate({opacity:'1'},800,'easeInQuint');
});

Have you tried setting the cycle's parent container style to display:none; visiblity:hidden;
And then once the page is loaded, $('div.container').show(); ?
That way, by default the HTML will be hidden and will not render on the screen until the page is loaded.

Related

Popup content will not appear in the UI - CartoDB Web Mapping Application

I am trying to add content to my popup in my web mapping application, but no content will appear in the popup when it is clicked. Perhaps something wrong with my JSAny help would be fantastic!
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Pop-ups | CARTO</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Open+Sans:300,400,600" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700' rel='stylesheet' type='text/css'>
<!-- Include Leaflet -->
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css" rel="stylesheet">
<!-- Include CARTO.js -->
<script src="https://libs.cartocdn.com/carto.js/v4.1.11/carto.min.js"></script>
<link href="https://carto.com/developers/carto-js/examples/maps/public/style.css" rel="stylesheet">
</head>
<body>
<div id="map"></div>
<aside class="toolbox">
<div class="box">
<header>
<h1>Pop-Ups</h1>
<button class="github-logo js-source-link"></button>
</header>
<section>
<p class="description open-sans">Create pop-up information windows and interact with your map.</p>
</section>
<footer class="js-footer"></footer>
</div>
</aside>
<script>
const map = L.map('map').setView([30, 0], 3);
map.scrollWheelZoom.disable();
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
const client = new carto.Client({
apiKey: 'default_public',
username: 'cartojs-test'
});
const populatedPlacesSource = new carto.source.Dataset(`
ne_10m_populated_places_simple
`);
const populatedPlacesStyle = new carto.style.CartoCSS(`
#layer {
marker-width: 7;
marker-fill: #EE4D5A;
marker-line-color: #FFFFFF;
}
`);
const populatedPlacesLayer = new carto.layer.Layer(populatedPlacesSource, populatedPlacesStyle, {
featureOverColumns: ['name', 'pop_max', 'pop_min']
});
client.addLayer(populatedPlacesLayer);
client.getLeafletLayer().addTo(map);
const popup = L.popup({ closeButton: false });
function openPopup(featureEvent) {
const data = featureEvent.data;
let content = '<div class="widget">';
// My popup up content
content += `<h3> ${data.name} </h3>`;
content += `<p>Between ${data.pop_min} and ${data.pop_max} inhabitants </p>`;
content += `</div>`;
popup.setLatLng(featureEvent.latLng);
if (!popup.isOpen()) {
popup.openOn(map);
}
}
function closePopup(featureEvent) {
popup.removeFrom(map);
}
populatedPlacesLayer.on('featureClicked', openPopup);
</script>
</body>
</html>
And here are the results in the Web Viewer. Note that I am not getting any errors thrown in the Console (image attached to this ticket)
I was expecting the content associated the dataset to appear in the popup ui
enter image description here
You are missing one line of code. The line that set the actual popupContent. After popup.setLatLng(featureEvent.latLng);
include: popup.setContent(content);
<!DOCTYPE html>
<html>
<head>
<title>Pop-ups | CARTO</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Open+Sans:300,400,600" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700' rel='stylesheet' type='text/css'>
<!-- Include Leaflet -->
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css" rel="stylesheet">
<!-- Include CARTO.js -->
<script src="https://libs.cartocdn.com/carto.js/v4.1.11/carto.min.js"></script>
<link href="https://carto.com/developers/carto-js/examples/maps/public/style.css" rel="stylesheet">
</head>
<body>
<div id="map"></div>
<aside class="toolbox">
<div class="box">
<header>
<h1>Pop-Ups</h1>
<button class="github-logo js-source-link"></button>
</header>
<section>
<p class="description open-sans">Create pop-up information windows and interact with your map.</p>
</section>
<footer class="js-footer"></footer>
</div>
</aside>
<script>
const map = L.map('map').setView([30, 0], 3);
map.scrollWheelZoom.disable();
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
const client = new carto.Client({
apiKey: 'default_public',
username: 'cartojs-test'
});
const populatedPlacesSource = new carto.source.Dataset(`
ne_10m_populated_places_simple
`);
const populatedPlacesStyle = new carto.style.CartoCSS(`
#layer {
marker-width: 7;
marker-fill: #EE4D5A;
marker-line-color: #FFFFFF;
}
`);
const populatedPlacesLayer = new carto.layer.Layer(populatedPlacesSource, populatedPlacesStyle, {
featureOverColumns: ['name', 'pop_max', 'pop_min']
});
client.addLayer(populatedPlacesLayer);
client.getLeafletLayer().addTo(map);
const popup = L.popup({
closeButton: false
});
function openPopup(featureEvent) {
const data = featureEvent.data;
let content = '<div class="widget">';
// My popup up content
content += `<h3> ${data.name} </h3>`;
content += `<p>Between ${data.pop_min} and ${data.pop_max} inhabitants </p>`;
content += `</div>`;
popup.setLatLng(featureEvent.latLng);
popup.setContent(content);
if (!popup.isOpen()) {
popup.openOn(map);
}
}
function closePopup(featureEvent) {
popup.removeFrom(map);
}
populatedPlacesLayer.on('featureClicked', openPopup);
</script>
</body>
</html>

JS works on CodePen but not locally [duplicate]

This question already has answers here:
Why is simple JavaScript code not running?
(3 answers)
Closed 1 year ago.
I'm trying to get a JS slider to work. I'm using Brackets as my code environment.
I have tried creating a local .js file and putting
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
<script type="text/javascript" src="my.js"></script>
line in <head>
I have also tried just putting only <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"> in <head> and then putting all of the script code within a <script> tag in <head>.
CodePen for that:
https://codepen.io/hiarooo/pen/zYNboJq
As you can see, the slider doesn't function properly.
However, I have noticed that if I simply put the code in the JS box of CodePen (I have commented it, but you can try uncommenting it to see what I mean) then the Slider functions perfectly.
What is wrong with the way I am doing things? I do not understand.
Thank you for any advice.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crypter | Upload01</title>`enter code here`
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght#700&display=swap" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!--<script type="text/javascript" src="my.js"></script>-->
</head>
<body>
<section class="section-slider">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Anton' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Neucha' rel='stylesheet' type='text/css'>
<div id="wrapper">
<div id="slider-wrap">
<ul id="slider">
<li data-color="#1abc9c">
<div>
<h3>What is cat</h3>
<span>it is a cat</span>
</div>
<i></i>
</li>
<li data-color="#3498db">
<div>
<h3>Slide #2</h3>
<span>Sub-title #2</span>
</div>
<i class="fa fa-gears"></i>
</li>
<li data-color="#9b59b6">
<div>
<h3>Slide #3</h3>
<span>Sub-title #3</span>
</div>
<i class="fa fa-sliders"></i>
</li>
<li data-color="#34495e">
<div>
<h3>Slide #4</h3>
<span>Sub-title #4</span>
</div>
<i class="fa fa-code"></i>
</li>
<li data-color="#e74c3c">
<div>
<h3>Slide #5</h3>
<span>Sub-title #5</span>
</div>
<i class="fa fa-microphone-slash"></i>
</li>
</ul>
<!--controls-->
<div class="btns" id="next"><i class="fa fa-arrow-right"></i></div>
<div class="btns" id="previous"><i class="fa fa-arrow-left"></i></div>
<div id="counter"></div>
<div id="pagination-wrap">
<ul>
</ul>
</div>
<!--controls-->
</div>
</div>
</section>
<script>
//current position
var pos = 0;
//number of slides
var totalSlides = $('#slider-wrap ul li').length;
//get the slide width
var sliderWidth = $('#slider-wrap').width();
$(document).ready(function(){
/*****************
BUILD THE SLIDER
*****************/
//set width to be 'x' times the number of slides
$('#slider-wrap ul#slider').width(sliderWidth*totalSlides);
//next slide
$('#next').click(function(){
slideRight();
});
//previous slide
$('#previous').click(function(){
slideLeft();
});
/*************************
//*> OPTIONAL SETTINGS
************************/
//automatic slider
var autoSlider = setInterval(slideRight, 3000);
//for each slide
$.each($('#slider-wrap ul li'), function() {
//set its color
var c = $(this).attr("data-color");
$(this).css("background",c);
//create a pagination
var li = document.createElement('li');
$('#pagination-wrap ul').append(li);
});
//counter
countSlides();
//pagination
pagination();
//hide/show controls/btns when hover
//pause automatic slide when hover
$('#slider-wrap').hover(
function(){ $(this).addClass('active'); clearInterval(autoSlider); },
function(){ $(this).removeClass('active'); autoSlider = setInterval(slideRight, 3000); }
);
});//DOCUMENT READY
/***********
SLIDE LEFT
************/
function slideLeft(){
pos--;
if(pos==-1){ pos = totalSlides-1; }
$('#slider-wrap ul#slider').css('left', -(sliderWidth*pos));
//*> optional
countSlides();
pagination();
}
/************
SLIDE RIGHT
*************/
function slideRight(){
pos++;
if(pos==totalSlides){ pos = 0; }
$('#slider-wrap ul#slider').css('left', -(sliderWidth*pos));
//*> optional
countSlides();
pagination();
}
/************************
//*> OPTIONAL SETTINGS
************************/
function countSlides(){
$('#counter').html(pos+1 + ' / ' + totalSlides);
}
function pagination(){
$('#pagination-wrap ul li').removeClass('active');
$('#pagination-wrap ul li:eq('+pos+')').addClass('active');
}
</script>
</body>
Try putting this way it works fine,because If you have code in your JavaScript that alters HTML as soon as the JavaScript file loads, there won't actually be any HTML elements available for it to affect DOM yet, so it will seem as though the JavaScript code isn't working, and you may get errors.Thanks :)

I have a jquery issue. I have two divs showing and hiding. Both are set to refresh but one is overriding it

I have a jquery issue I have two divs showing and hiding and both are set to refresh but one is over riding the other. I am not sure why the load1 were div1 is at keeps overriding the load2 div2. so when i click on button completed the received div is automatically refreshing and changing the page back to received. I will try to get this on fiddle.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="http://localhost/test/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="http://localhost/test/assets/css/custom.css" rel="stylesheet">
<link href="http://localhost/test/assets/css/custom_edit.css" rel="stylesheet">
<link href="http://localhost/test/assets/datatables/css/dataTables.bootstrap.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<pre><button class="btn btn-sm btn-primary" id="received">Received</button><button class="btn btn-sm btn-success" id="completed">Completed</button></pre>
<div id="load1">
<div id="div1">
<h3>Received Section</h3>
//code goes here......
</div>
</div>
<div id="load2">
<input type="hidden" id="show_completed" value="1" name="show_completed">
<div id="div2">
<h3>Completed Section</h3>
//code goes here......
</div>
</div>
<footer>
<script src="http://localhost/test/assets/jquery/jquery-3.1.0.min.js"></script>
<script src="http://localhost/test/assets/bootstrap/js/bootstrap.min.js"></script>
<script src="http://localhost/test/assets/datatables/js/jquery.dataTables.min.js"></script>
<script src="http://localhost/test/assets/datatables/js/dataTables.bootstrap.js"></script>
<script type="text/javascript">
var $show_completed = document.getElementById('show_completed');
if($show_completed.value == '0')
{
setInterval(function() {
$("#load1").load(location.href+" #load1>*","");
}, 10000); // seconds to wait, miliseconds
}
else($show_completed.value == '1')
{
setInterval(function() {
$("#load2").load(location.href+" #load2>*","");
}, 100000); // seconds to wait, miliseconds
}
</script>
<script type="text/javascript">
$(document).ready( function () {
$('#div2').fadeOut();
} );
$("#received").on('click', function() {
document.getElementById("show_completed").value='0';
$("#div1").fadeIn();
$("#div2").fadeOut();
});
$("#completed").on('click', function() {
document.getElementById("show_completed").value='1';
$("#div2").fadeIn();
$("#div1").fadeOut();
});
</script>
</footer>
</body>
</html>
Try this... Hope it helps
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="http://localhost/test/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="http://localhost/test/assets/css/custom.css" rel="stylesheet">
<link href="http://localhost/test/assets/css/custom_edit.css" rel="stylesheet">
<link href="http://localhost/test/assets/datatables/css/dataTables.bootstrap.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="http://localhost/test/assets/bootstrap/js/bootstrap.min.js"></script>
<script src="http://localhost/test/assets/datatables/js/jquery.dataTables.min.js"></script>
<script src="http://localhost/test/assets/datatables/js/dataTables.bootstrap.js"></script>
</head>
<body>
<pre>
<button class="btn btn-sm btn-primary" id="received">Received</button>
<button class="btn btn-sm btn-success" id="completed">Completed</button>
</pre>
<div id="load1">
<div id="div1">
<h3>Received Section</h3>
//code goes here......
</div>
</div>
<div id="load2">
<input type="hidden" id="show_completed" value="1" name="show_completed">
<div id="div2">
<h3>Completed Section</h3>
//code goes here......
</div>
</div>
<script type="text/javascript">
var $show_completed = document.getElementById('show_completed');
if($show_completed.value == '0'){
setInterval(function() {
$("#load1").load(location.href+" #load1>*","");
}, 10000); // seconds to wait, miliseconds
} else($show_completed.value == '1'){
setInterval(function() {
$("#load2").load(location.href+" #load2>*","");
}, 100000); // seconds to wait, miliseconds
}
</script>
<script type="text/javascript">
$(document).ready( function () {
$('#div2').fadeOut();
});
$("#received").on('click', function() {
document.getElementById("show_completed").value='0';
$("#div1").fadeIn();
$("#div2").fadeOut();
});
$("#completed").on('click', function() {
document.getElementById("show_completed").value='1';
$("#div2").fadeIn();
$("#div1").fadeOut();
});
</script>
</body>
</html>

Angularjs fails to dynamic change image src

Hello i'm building an application where i want to dynamically change the source of an image in order to force reload it . The problem is that in order of this i only get a broken image on the browser. Instead , if a run the function manually by a button it runs perfect .
HTML document
<!DOCTYPE html>
<html lang="en" ng-app='cameraApp'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Node JS Camera</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src='https://code.angularjs.org/1.4.4/angular-sanitize.min.js'></script>
<script src="cameraApp.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="jumbotron">
<h1>Welcome to NodeJS Camera v1</h1>
</div>
<div ng-controller="HomeController">
<div class="cameraControl col-md-5">
<p>Here is the camera control</p>
<button class="btn btn-default" ng-click="getSnapshot()">Snapshot</button>
<button class="btn btn-info" ng-click="intervalFunction()">Start Feed</button>
</div>
<div class="lifeFeed col-md-7">
<p>Here is the live feed</p>
<p><button class="btn btn-default" ng-click="readSnapshot()">Snapshot Read</button></p>
<img width='600' height='600' ng-src="{{snapshot}}" alt="SnapShot taken">
</div>
</div>
</div>
</body>
</html>
cameraApp.js
var cameraApp = angular.module('cameraApp',[]);
cameraApp.controller('HomeController', function($scope,$http,$timeout) {
function updateImage() {
var img = 'snapshots/camera.jpg'+ '?decache=' + Math.random();
console.log('Snapshot Loaded');
$scope.snapshot = img;
};
$scope.readSnapshot = updateImage;
$scope.getSnapshot = function() {
$http.get('/api/getSnapshot')
.then(function(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Snapshot captured');
$scope.readSnapshot();
}, function(response) {
console.log('Error in capturing...');
});
}
$scope.intervalFunction = function() {
$timeout(function() {
$scope.getSnapshot();
$scope.intervalFunction();
}, 2000);
};
// Kick off the interval
$scope.intervalFunction();
});
There are two solutions I've used for this in the past.
1) Use an ng-if/ng-show on your img tag. This will prevent the broken image from displaying.
<img ng-if='snapshot'>
2) Set a default image that will load and then be replaced once the other images load.
$scope.snapshot = 'snapshots/default.png';

click event not happening with bootstrap panel

I'm trying to make my own class with panels that open and close content using Bootstrap and jQuery (not an accordion, I want multiple open at a time). However, the click event isn't working for me and I have no idea why... I tried the "*" selector and the alert was working but it's not working when I try to associate it with specific elements.
Practice2.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Practice 2</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../static/css/prism.css">
<link rel="stylesheet" href="../static/css/styles.css">
<script src="../static/js/prism.js"></script>
<script src="../static/js/script.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="panel panel-default panel-toggle" id="demo">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code><br>
Explanation
</div>
</div>
</div>
</body>
</html>
script.js
// $(".panel-toggle:panel-header").click(function(){
// // $(this).next().toggle();
// alert("hello");
// });
$("#demo").click(function(){
alert("hello");
});
styles.css
.panel-toggle .panel-heading:after {
font-family:'Glyphicons Halflings';
content:"\e114";
float: right;
color: grey;
}
.panel-toggle .collapsed:after {
content:"\e080";
}
.panel-toggle .panel-body {
}
Clearly the rest of the code needs some adjustment but I'm just troubleshooting this part right now and would appreciate some advice on what I'm missing. Thanks!
With
HTML
<div class="panel panel-default panel-toggle">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code>
Explanation
</div>
</div>
JS
$(document).ready(function(){
$(".panel-heading").click(function(){
$(this).next().toggle("slow");
});
});
works
JSFiddle demo
You should put your jQuery code in document.ready block ensure your code working after those element been generated.
Script.js should be changed like this.
$(document).ready(function(){
$("#demo").click(function(){
alert("hello");
});
});

Categories

Resources