Smooth scroll Javascript works but messes up flask app - javascript

Im working on a flask app and in my index.html I have a js file that has a smooth scrolling script in it. The smooth scroll works as far as clicking on links and the page goes to that section nice and smooth, but I have a web form that Im trying to process with flask. When I run the app.py and then go to the url it gives my sites loads, but if I fill out the form and submit nothing happens. I get an error in dev console:
uncaught TypeError: Cannot read property 'top' of undefined
at HTMLInputElement.<anonymous> (main.js:33)
at HTMLInputElement.dispatch (jquery-3.4.1.min.js:2)
at HTMLInputElement.v.handle (jquery-3.4.1.min.js:2)
When I comment out the smooth scroll code and run the app, the form works correctly when I click submit. App.py prints out my data and the success page is loaded. The problem is the smooth scroll but I dont know why, because again it actually does smooth scroll but when the code is active but it wont let the submit work.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://kit.fontawesome.com/b015121141.js"></script>
<link rel="stylesheet" href="../static/css/style.css">
<link rel="stylesheet" media="screen and (max-width: 768px)" href="../static/css/mobile.css">
<link rel="stylesheet" media="screen and (min-width: 1100px)" href="../static/css/widescreen.css">
<title>System Services</title>
</head>
<body id="home">
<nav id="navbar">
<h1 class="logo">
<span class="text-primary">
<i class="fas fa-robot"></i>
</span>Systems
</h1>
<ul>
<li>Home</li>
<li>What</li>
<li>Who</li>
<li>Contact</li>
</ul>
</nav>
<!-- header: Showcase -->
<header id="showcase">
<div class="showcase-content">
<h1 class="l-heading">
Take me to your leader
</h1>
<p class="lead">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptates alias quasi eligendi. Itaque, repudiandae
obcaecati accusamus harum nesciunt possimus magni?
</p>
Read More
</div>
</header>
<!-- Section: Contact-->
<section id="contact">
<div class="contact-form bg-primary p-2">
<h2 class="m-heading">Contact Us</h2>
<p>Please Use the form below to contact us</p>
<form action="/submit" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Enter Email">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone" placeholder="Enter Phone">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" id="" placeholder="Enter Message"></textarea>
</div>
<input type="submit" value="Submit" class="btn btn-dark">
</form>
</div>
<div class="map"></div>
</section>
<!-- Footer -->
<footer id="main-footer" class="bg-dark text-center py-1">
<div class="container">
<p>Copyright © 2019, All Rights Reserved</p>
</div>
</footer>
<!-- JQuery CDN -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<!-- Local Js file -->
<script src="../static/js/main.js"></script>
<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=[api]&callback=initMap"
async defer></script>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Success</title>
</head>
<body>
<H1>Success!!</H1>
</body>
</html>
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/submit', methods=['POST'])
def submit():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
phone = request.form['phone']
message = request.form['message']
print(name, email, phone, message)
return render_template('success.html')
if __name__ == '__main__':
app.debug = True
app.run()
main.js
//init and add the map
function initMap() {
// your location
const loc = { lat: 42.964890, lng: -88.183040 };
// centered map on location
const map = new google.maps.Map(document.querySelector('.map')
, {
zoom: 10,
center: loc
});
// the marker, positioned at location
const marker = new google.maps.Marker({ position: loc, map: map });
}
// Sticky menu background
window.addEventListener('scroll', function () {
if (window.scrollY > 150) {
document.querySelector('#navbar').style.opacity = 0.88;
} else {
document.querySelector('#navbar').style.opacity = 1;
}
})
// Smooth Scrolling
$('#navbar a, .btn').on('click', function (event) {
if (this.hash !== '') {
event.preventDefault();
const hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top - 100
},
800
);
}
});

The problem is really related on jquery forum and don't came from flask. Nevertheless, they are solutions :
Solution #1:
Use the native css smooth scroll (works fine in your case in my opinion) --> Smooth scroll
Solution #2 :
Try to call animate() in console of your website and paste it belowthe result to see where the problem came from :)
I hope this will help you I tried on my computer and I can figure any other solutions !

You have the line this.hash inside your click event which will always return "" and that is the reason you are getting the error because you have the hash/id in the href attribute of the links and buttons where you are binding the click event
<ul>
<li>Home</li>
<li>What</li>
<li>Who</li>
<li>Contact</li>
</ul>
<input type="submit" value="Submit" class="btn btn-dark">
Read More
and you just need to change the
this.hash
to
$(this).attr('href')
OR
this.href
your click event should look like this
// Smooth Scrolling
$('#navbar a, .btn').on('click', function (event) {
if (this.href !== '') {
event.preventDefault();
const hash = this.href;
$('html, body').animate({
scrollTop: $(hash).offset().top - 100
},
800
);
}
});

Related

How to populate different category data from the same api at the DOM using javascript?

I'm currently working with news API and trying to populate different category (i.e sports, science, business etc) under different heading on the same page of the website, but failed to do so. Here I tried to use template literal, as first created a template literal in the api named category and initiated it using let. So there are two sections "Trending Blogs" and "You May Like" so here I wanna show two different category in the two different section respectively. Here I'm attaching the code in the following.
Here is the code in html
`<!DOCTYPE html>
<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" />
<link rel="stylesheet" href="/styles/utils.css" />
<link rel="stylesheet" href="/styles/navbar.css" />
<link rel="stylesheet" href="/styles/body.css" />
<script
src="https://kit.fontawesome.com/e582ecfb98.js"
crossorigin="anonymous"
></script>
<title>Document</title>
</head>
<body>
<!-- <h1>This is a blog site</h1> -->
<!-- Navbar starts from here -->
<nav class="navigation max-width-0 m-auto">
<div class="middle">
<b> Blogsite</b>
</div>
<div class="left">
<ul>
<li><a class="header-elements" href="./index.html">Home</a></li>
<li><a class="header-elements" href="./about.html">About</a></li>
<li><a class="header-elements" href="./contact.html">Contact</a></li>
</ul>
</div>
<div class="right">
<input type="text" placeholder="Article Search" />
<button class="btn"><i class="fa fa-magnifying-glass"></i></button>
</div>
</nav>
<!-- Navbar ends -->
<!-- body starts -->
<div class="content max-width-1 m-auto">
<h1 class="land-heading">Welcome to Blogsite</h1>
<p class="intro">
Atameo allows travellers to capture their trips in a completely new way.
It records your route, adds your photos, videos and music and turns your
adventures into your personal travel profile. Have all your travel
experiences in one place and find out more about your travel style by
diving into your personal travel statistics: How far did you travel last
year? What’s the highest point you have been to? How much of the world
have you seen? Inspire others to go out and explore, while getting
inspired by some of the most daring journeys of our time. Explore.
Capture. Inspire.
</p>
<hr />
<h1 class="land-heading">Trending Blogs</h1>
<div class="blog-section" id="blog-section">
</div>
<h1 class="land-heading">You may like</h1>
<div class="blog-section" id="blog-section2">
</div>
<h1 class="land-heading">Categories</h1>
<div class="blog-section" id="category">
<div class="r1c1 block">
<a href=""
><img
class="img"
src="https://www.nomadicmatt.com/wp-content/uploads/2022/07/parisnm3.jpeg"
alt="img"
/>
<p class="blog-title">NM+ Weekly Update: Europe Edition</p></a
>
</div>
</div>
</div>
<!-- Body ends -->
<!-- Footer starts -->
<div class="footer m-auto">
<label for="">Feedback</label>
<input type="text" class="" placeholder="First Name" />
<input type="text" placeholder="e-mail" />
<button type="submit" class="btn btn-foot">Send Feedback</button>
</div>
<div class="m-auto copyright">
<p>copyright 2022 #md_arif</p>
</div>
<!-- Footer ends -->
<script src="./scripts/app.js"></script>
</body>
</html>
`
Here is the code of vanilla-js
console.log("Here we go");
let blogSection = document.getElementById("blog-section");
let blogSection2 = document.getElementById("blog-section2");
function generateCards(e) {
const newXHRRequest = new XMLHttpRequest();
// let source = 'the-times-of-india';
let apikey = '75da3b7678de41fcb76359935aabdc3d'
let category = '';
newXHRRequest.open(
"GET",
`https://newsapi.org/v2/top-headlines?country=in&category=${category}&pagesize=3&apiKey=${apikey}`,
true
);
newXHRRequest.getResponseHeader("content-type", "application/json");
newXHRRequest.onload = function () {
if (this.status === 200) {
let myCards = JSON.parse(this.responseText);
console.log(myCards);
let articles = myCards.articles;
// console.log(articles);
let itemsHtml = "";
articles.forEach((element) => {
// console.log(articles);
// category="sports";
console.log(element);
let items = `<div class="r1c1 block">
<a href="${element["url"]}" target="_blank"><img class="img" src=${element["urlToImage"]} alt="img">
<p class="blog-title">${element["title"]}</p></a>
</div>`;
itemsHtml += items;
});
blogSection.innerHTML = itemsHtml;
blogSection2.innerHTML = itemsHtml;
} else {
console.log("Some error occured");
}
};
newXHRRequest.send();
}
generateCards();

Maintain colllapse-state after refresh

In my Sidebar I included a collapse button to show/hide a form. Now I want to maintain the collapse-state when refreshing the page:
If the form was un-collapsed before refreshing the page, it must stay like this after the refresh.
I think I need to use the localStrorage in JavaScript, but I actually don't know how to use this.
This is my HTML:
<!-- Sidebar -->
<ul class="sidebar navbar-nav">
<li class="nav-item active">
<a class="nav-link" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
<i class="fa fa-filter"></i>
<span>Search Filter</span>
</a>
</li>
</ul>
<!-- Form -->
<div class="collapse" id="collapseExample">
<form>
......
</form>
I found some code only but it seems like it does not work for me..:
var shown = []
// On collapse
shown.remove($(this).attr('id'));
localStorage.setItem('shown', shown);
// On open
shown.push($(this).attr('id'));
localStorage.setItem('shown', shown);
// On page load
var shown = localStorage.getItem('shown');
for (var s in shown) {
$('#collapseExample' + s).show();
}
Thanks for your help!
Here's a Bootstrap 4 collapse example that works. The main difference from the starter template is that I moved the jQuery import to the top of the file so that I could use the document.load function. I've added comments to the code but if anything's still not clear, keep asking questions. Note that I left the vanilla javascript answer for historical comments and in case it helps you, too.
I used the starter page from here:
https://getbootstrap.com/docs/4.0/getting-started/introduction/
And the first collapse example from here:
https://getbootstrap.com/docs/4.0/components/collapse/
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
<title>Hello, world!</title>
<!-- jQuery -->
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"
></script>
<script>
$(function() {
// store a reference to the collapse div so that
// we don't have to keep looking it up in the dom
const collapseExample = $("#collapseExample");
// register a callback function to the collapse div that
// will be called every time the collapse is opened.
collapseExample.on("shown.bs.collapse", function() {
// since we know that that this function is called on
// open, we'll set the localStorage value to "show"
localStorage.setItem("collapseExample", "show");
});
// register a callback function to the collapse div that
// will be called every time the collapse is closed.
collapseExample.on("hidden.bs.collapse", function() {
// since we know that that this function is called on
// open, we'll set the localStorage value to "hide"
localStorage.setItem("collapseExample", "hide");
});
// Since this function runs on page load (meaning only once), we can
// check the value of localStorage from here and then call the
// bootstrap collapse methods ourselves:
// Check the value of the localStorage item
const showExampleCollapse = localStorage.getItem("collapseExample");
// Manipulate the collapse based on the value of the localStorage item.
// Note that the value is determined by lines 36 or 44. If you change those,
// then make sure to check that the comparison on the next line is still valid.
if (showExampleCollapse === "show") {
collapseExample.collapse("show");
} else {
collapseExample.collapse("hide");
}
});
</script>
</head>
<body>
<main>
<p>
<a
class="btn btn-primary"
data-toggle="collapse"
href="#collapseExample"
role="button"
aria-expanded="false"
aria-controls="collapseExample"
>
Link with href
</a>
<button
class="btn btn-primary"
type="button"
data-toggle="collapse"
data-target="#collapseExample"
aria-expanded="false"
aria-controls="collapseExample"
>
Button with data-target
</button>
</p>
<div class="collapse" id="collapseExample">
<div class="card card-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus
terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer
labore wes anderson cred nesciunt sapiente ea proident.
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- Popper.js, then Bootstrap JS -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"
></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"
></script>
</body>
</html>
END BOOTSTRAP ANSWER
BEGIN VANILLA JAVASCRIPT ANSWER
Here's a basic, self-contained version of what you seem to be trying to do. It's not pretty, but hopefully, it's clear.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
function getCollapsed() {
const state = localStorage.getItem('collapsed');
if(state === 'collapsed'){
return true;
}
return false;
}
function getStatus(){
const resultDiv = document.getElementById('result');
const isCollapsed = getCollapsed();
if(isCollapsed){
resultDiv.innerHTML = "collapsed";
}else{
resultDiv.innerHTML = "un-collapsed";
}
}
function toggleCollapse(){
const isCollapsed = getCollapsed();
if(isCollapsed){
localStorage.setItem('collapsed', 'un-collapsed');
}else{
localStorage.setItem('collapsed', 'collapsed');
}
getStatus();
}
</script>
</head>
<body onload="getStatus()">
<div>
<button onclick="toggleCollapse()">Toggle Collapse</button>
</div>
<div id="result"></div>
</body>
</html>

JavaScript code doesn't execute in the browser

I'm trying to learn programming from various online tutorials and I created flask server which predicts something. I also got the front-end with javascript but it wont run. I don't know why. I don't know JS. I know python well but that's it.
I don't know that to do.
here is the html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="static/style.css">
<script type="text/javascript", src="static/code.js"></script>
<title>Heading</title>
</head>
<body>
<br>
<!--<img class="logo" src="static/final_v1.png" alt="">-->
<br>
<div class="container main">
<div class="jumbotron" id="holder">
<h1 class='main_heading'> Some Machine learning model</h1>
<h3>lorem ipsum dolor sit amet</h3>
<br>
<div class="instructions">
<h2>Instructions: </h2>
<p>1. lorem ipsum dolor sit amet</p>
<p>2. Curabitur tincidunt orci non nunc sagittis euismod.</p>
</div>
<br>
<br>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Feature1:</label>
<div class="col-sm-10">
<input class="form-control" id="feature1" placeholder=" Enter feature1" >
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="button btn btn-default">Submit</button>
</div>
</div>
</form>
<h2 class="result"></h2>
</div>
</div>
<!-- Footer -->
<footer class="page-footer font-small blue">
<div class="footer-copyright text-center py-3">
<div class="bottom">
<p>xyz | Status Prediction Demo</p>
</div>
</div>
</footer>
<!-- Footer -->
</body>
</html>
here is the JS file:
var feature1;
$(document).ready(function(){
// fetch all DOM elements for the input
feature1_ = document.getElementById("feature1");
;
});
$(document).on('click','#submit',function(){
alert('end')
// on clicking submit fetch values from DOM elements and use them to make request to our flask API
var feature1 = feature1_.value;
if(feature1 == ""){
// you may allow it as per your model needs
// you may mark some fields with * (star) and make sure they aren't empty here
alert("empty fields not allowed");
}
else{
var requestURL = "http://127.0.0.1/predict?f1="+feature1;
console.log(requestURL); // log the requestURL for troubleshooting
$.getJSON(requestURL, function(data) {
console.log(data); // log the data for troubleshooting
prediction = data['json_key_for_the_prediction'];
});
// following lines consist of action that would be taken after the request has been read
// for now i am just changing a <h2> tag's inner html using jquery
// you may simple do: alert(prediction);
alert(prediction)
$(".result").html("Prediction is:" + prediction);
}
});
There is flask on the backend and js suppose to execute the link.
I have no idea why this is not working
Could you help me please ?
OK, there are several things:
Your submit button is missing an id
Your submit button causes reload
Your callback will run before you get a response
Change your HTML to:
<button id="submit" type="button" type="button" class="button btn btn-default">Submit</button>
The type attribute will remove the reload and the added id will make your script recognize it.
These lines of code runs before you get a response:
alert(prediction)
$(".result").html("Prediction is:" + prediction);
Put them inside getJSON:
$.getJSON(requestURL, function(data) {
console.log(data); // log the data for troubleshooting
var prediction = data['json_key_for_the_prediction']; // <-- added `var`
alert(prediction);
$(".result").html("Prediction is:" + prediction);
});
You're clearly new so I'm offering a strict/minimal test case file for you to work with. This one will simply trigger an alert when the page loads.
Download Notepad++ so you're not adding BOM (Byte Order Marks) if you're running a Microsoft operating system.
Save the following code as example.xhtml.
Modify as needed.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Default Test Template</title>
<script defer="true" type="application/javascript">
//<![CDATA[
window.onload = function(event)
{
alert('JavaScript is enabled');
}
//]]>
</script>
<style type="text/css">
body {background-color: #000; color: #fff;}
</style>
</head>
<body>
<h1>Default Test Template</h1>
</body>
</html>

How to reload javascript without refreshing the page?

I have a webpage that links some javascript via tags. The script is amazon-localiser.js which will change an amazon link to one appropriate for the visitor. e.g. an Amazon.com link will swap to amazon.co.uk for a UK visitor or Amazon.de for a german visitor.It also appends to the link the relevant amazon affiliate link.
When the user lands on the page they click through some options (javascript) however by the time you reach an amazon link the page must be refreshed for the amazon-localiser.js script to work. I have tried using a page refresh in HTML but this sends me back to the very beginning of the questions. How do I reload the javascript without affecting the users location on the site?
The site is www.wfbsir.com, if you select "Scifi" then "Maybe" you will get to an amazon.com link, if you hover over it you will see it links to amazon.com if you refresh the page it will show you the link to your local store with an affiliate link appended.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>What book should I read?</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="app.css" />
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row">
<div class="col-xs-12 text-right">
<button class="btn btn-default btn-corner" type="submit" data-bind="click: startOver, visible: queryData().id > 0">Start over</button>
</div>
</div>
</div>
<div class="container main">
<div class="row">
<div class="c12 text-center">
<h1 data-bind="text: queryData().text"></h1>
<h3 data-bind="text: queryData().subhead"></h3>
<h3><a data-bind="text: queryData().link, attr: {href: url}"></a></h3>
<div class="option-group" data-bind="foreach: queryData().answers">
<button class="btn btn-default btn-lg" type="submit" data-bind="click: $parent.goToTarget, text: text"></button>
</div>
<button class="btn btn-default" type="submit" data-bind="click: stepBack, visible: navHistory().length > 1">Previous Step</button>
<button class="btn btn-default" type="submit" data-bind="click: buyBook, visible: navHistory().length > 1">Buy the book</button>
</div>
</div>
</div>
<div class="push"></div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
<script src="app.js?v=0.4.0"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="amazon-localiser.js"></script>
<script>
</script>
I have tried using jQuery getScript and also window.location.reload(); but neither reload just the javascript, the only thing that I can find to work is F5/Refresh.
I noticed that the amazon-localiser.js invokes the function findLocation onload of the page, as you can see below.
if (window.addEventListener) {
window.addEventListener("load", findLocation, false)
} else {
window.attachEvent("onload", findLocation)
}
So, a possible solution to your problem, could be to invoke this function again when you need to update your amazon link.
I tried invoking it from the console and it works, so try to invoke findLocation() manually when needed and see if it serves your scope.
Simone
You can add dynamically script on the page with some condition, for example:
var script = document.createElement('script');
var src;
if (true) {
src = 'amazon.co.uk';
} else {
src = 'amazon.com';
}
script.src = src;
document.head.appendChild(script);
As gnllucena told, you can view the question or there is the solution.
Build the loader function:
Put the following code in the document
<script type="text/javascript">
function LoadMyJs(scriptName) {
var docHeadObj = document.getElementsByTagName("head")[0];
var newScript= document.createElement("script");
newScript.type = "text/javascript";
newScript.src = scriptName;
docHeadObj.appendChild(newScript);
}
</script>
// place a button for reloading script.
<input type="button" name="reloadNewJs" value="Reload JavaScript" onClick="LoadMyJs('needed_script.js')">

Leaflet map requires page refresh to display in Jquery Mobile app

I'm currently in the middle of a project and have stumbled across a problem. I have one HTML file called index.html that holds the base functionality pages of my app(welcome page, login and register) and a second HTML page called home.html that you reach after successful login which is suppose to display a leaflet map with user location. Problem is when I successfully login the map does not show unless I refresh the page and this is undesirable.
For the past few days I have tried every combination of where to put the map JS on the second HTML page. I have tried putting the code inside script tags inside the div data-role section and I still need to refresh to see the map. I understand that JQM only calls the div data-role. The code is being called because I am prompted to allow location and if I log to the console the JS is being called but still no map.
Index.html
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- JQuery and JQuery mobile -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- Bootstrap -->
<!--<link rel="stylesheet" href="../resources/bootstrap/dist/css/bootstrap.min.css">
<script src="../resources/bootstrap/dist/js/bootstrap.min.js"></script>-->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!-- LeafletJS -->
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<!-- CSS & Scripts -->
<link rel="stylesheet" href="./css/index.css">
<link rel="stylesheet" href="./css/header.css">
</head>
<body>
<!-- Login Page Begin -->
<div data-role="page" id="loginPage">
<div data-role="main" class="ui-content">
<h2 class="text-center"><strong>Login to GeoBus</strong></h2>
<div class="loginForm">
<form method="post">
<fieldset data-role="controlgroup">
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input class="form-control" type="email" id="email" placeholder="user#user.com" required="required">
</div>
<div class="form-group">
<label for="password" class="control-label">Password</label>
<input class="form-control" type="password" id="password" placeholder="Enter a Password" required="required">
<br>
</div>
<div class="form-group">
<button type="submit" id="loginButton" value="Login">Login</button>
</div>
</fieldset>
</form>
<div class="alert alert-danger" id="failAlert">
</div>
</div>
</div>
</div>
<script src="./js/index.js"></script>
</body>
</html>
index.js
$('#loginButton').click(function () {
var passwordStrengthRegex = /((?=.*d)(?=.*[a-z])(?=.*[A-Z]).{6,12})/gm;
var email = $("#email").val();
var pword = $("#password").val();
if(!pword.match(passwordStrengthRegex) && pword.length != 0){
$('#failAlert').html("<center>Password Rules: 6-12 Characters & At Least 1 Uppercase, 1 Lowercase, 1 Number.</center>");
hideShowAlert($('#failAlert'));
}
else if (email.length != 0 && pword.length != 0) {
var data = {
email: email,
password: pword
};
$.ajax({
type: "POST",
data: JSON.stringify(data),
url: "https://www.geobus.co.uk/api/v1/login",
success: function (data) {
if (data.error == false) {
sessionStorage.user = data.user;
sessionStorage.token = data.token;
$.mobile.pageContainer.pagecontainer("change", "home.html");
//$.mobile.changePage("home.html"); //,{reloadPage: true});
} else if (data.error == true) {
$('#failAlert').html("<center>Invalid Login Credentials!</center>");
hideShowAlert($('#failAlert'));
}
},
error: function (data) {
$('#failAlert').html("<center>Whoops Something Has Gone Wrong!</center>");
}
});
return false;
}
});
home.html
<body>
<div data-role="page" id="home">
<div data-role="panel" id="menu" data-swipe-close="true" data-display="overlay">
<ul class="nav navbar-nav" id="slideMenu">
<center>
<label class="menuLabel">Swipe to Close</label><span id="slideGlyph" class="glyphicon glyphicon-chevron-left"></span></center>
<li>Home</li>
<li>Track</li>
<li>Timetables</li>
<li>Routes</li>
<li>Log Out</li>
</ul>
</div>
<div data-role="header" class="ui-header">
<a href="#menu" class="navbar-toggle" role="button">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<img src="../images/logo.png" id="logo" alt="GeoBus Logo">
</div>
<div data-role="main" class="ui-content">
<div class="alert alert-success" id="successAlert">
Successfull Login!
</div>
<div id="map"></div>
<script>
map = L.map('map');
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var userIcon = L.icon({
iconUrl: '../images/userMapPin.png',
iconSize: [38, 85],
iconAnchor: [22, 94]
});
map.locate({
setView: true,
maxZoom: 18,
enableHighAccuracy: true
});
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
function onLocationFound(e) {
var radius = e.accuracy / 2;
L.marker(e.latlng, {
icon: userIcon
}).addTo(map)
.bindPopup("You are within " + radius + " meters of this point.").openPop$
}
function onLocationError(e) {
alert(e.message);
}
</script>
</div>
</div>
</body>
</html>
Sorry for the mess of code I have shortened it as much as possible. I did have the script tag code in home.html separated out into it's own file but I still needed a refresh. Has anybody got any idea where my problem is? I'm loosing my mind. Any help would be greatly appreciated.
I had this:
<div data-role="main" class="ui-content">
<div id="map"></div>
</div>
This was the fix.
<div id="map" data-role="main" class="ui-content">
Thanks for the help Omar.

Categories

Resources