How to reload javascript without refreshing the page? - javascript

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')">

Related

I want to delete all checked lists pressing the delete button but I don't know how

I'm learning Javascript and now I'm making to-do list.I've finished the basic one but I want to add the delete button which delete all the checked lists to my to-do list.
I've tried some ways that I came up with and they all failed and I cannot find the answer by googling.
How can I do this ? If there is someone who know, please teach me . I'd appreciated if you could show me how.
this is my code ↓ the error happened saying cannot read property 'parentElement' of null at Object.deleteAll
deleteAll: function() {
let taskListItem, checkBox, checkBoxParent;
for (i=0; i<this.taskListChildren.length; i++){
taskListItem = this.taskListChildren[i];
checkBox = taskListItem.querySelector('input[type = "checkbox"]:checked');
checkBoxParent = checkBox.parentElement;
checkBoxParent.remove();
}
document.getElementById('deleteChecked').addEventListener('click', () => {
tasker.deleteAll();
});
πŸ™
// this is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
<link rel="stylesheet" href="css/styles.css">
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
</head>
<body onLoad = "tasker.construct();">
<div class="tasker" id="tasker">
<div class="error" id="error">Please enter a task</div>
<div class="tasker-header" id="tasker-header">
<input type="text" id="input-task" placeholder ="Enter a task">
<button id="add-task-btn"><i class="fas fa-plus"></i></button>
</div>
<div class="tasker-body">
<ul id="tasks">
</ul>
</div>
<button id="deleteChecked">Delete</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
You can use the jQuery library and solve it as follows.
Step 1) Define in your html button element:
<button id="button" onclick="reset()"> RESET </button>
Step 2) define the 'reset ()' function, like this
function reset()
{
$("input:chceckbox").removeAttr("chcecked");
}
Good luck!!

Button won't redirect to given html page in location.href

I can't redirect to the next page. Please help me. I have a project due tomorrow. I've been trying for more than five hours. Please help me. I'm begging you guys. I don't know what I'm doing wrong. I'm very new to Javascript.
Please tell me what I'm doing wrong
document.getElementById("one").onclick = function() {
location.href = "lessons.html"
};
<!DOCTYPE html>
<html>
<head>
<title> MaxFluency Tutorials Page</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="tutorial.css">
</script>
</head>
<body>
<header>
<div class="topbar">
<center>
<p> Tutorials</p>
</center>
</header>
</div>
<div class="lessons">
<center>
<button class=les id=one type="button"> <h3> Lesson 1: </h3> Nature of Communication </button>
<button class=les id="2nd"> <h3>Lesson 2:</h3></button>
<button class="les" id="3rd"> <h3>Lesson 3:</h3></button>
</center>
</div>
<div class="nav">
<center><button class="loc"> Home</button>
<button class="loc"> Highscores </button>
<button class="loc"> Support us!</button>
</center>
</div>
<script type="text/Javascript" src="tutorials.js">
</script>
</body>
</html>
Your HTML is quite malformed, with some opening tags not closed anywhere, closing tags that do not have any matching tag, etc... This needs some tidying.
Also, if this Javascript code is in an external file, make sure it is wrapped in an onload event (making sure that all HTML elements actually loaded before calling document.getElementById). Finally, note the semicolon placement. You should place the semicolon after the statement, not after the function's ending }!
Side note: Why re-inventing the wheel when you can simply use an anchor tag (<a>) for redirecting?
onload = function() {
document.getElementById("one").onclick = function () {
console.log("clicked!");
location.href = "lessons.html";
}
}
<!DOCTYPE html>
<html>
<head>
<title> MaxFluency Tutorials Page</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="tutorial.css">
</head>
<body>
<header>
<div class="topbar">
<center> <p> Tutorials</p> </center>
</div>
</header> <!-- this closing tag was missing -->
<div class="lessons">
<center>
<button class=les id=one type="button" > <h3> Lesson 1: </h3> Nature of Communication </button>
<button class=les id="2nd"> <h3>Lesson 2:</h3></button>
<button class="les" id="3rd"> <h3>Lesson 3:</h3></button>
</center>
</div>
<div class="nav">
<center><button class="loc"> Home</button>
<button class="loc"> Highscores </button>
<button class="loc"> Support us!</button>
</center>
</div>
<script type="text/Javascript" src="tutorials.js"></script>
</body>
</html>
1) there is a lonely closing script tag in the head section.
2) your closing header and div tags before .lessons are in reverse order
3) Here is a fiddle that seems to be working. Button goes to a 404 just because the lessons.html doesn't exist here.
I also added a slash for a relative path. I assume you are probably working from a single root directory given that it is a tutorial but I could be wrong there.
location.href = "/lessons.html";
https://jsfiddle.net/y7txje5c/1/

how to prevent clicking on an image until all the scripts is fully loaded

I am working on an asp.net mvc web application which contain a web template similar to this web templete.
now i am facing this problem:-
let say a user access the image gallery , and while the page is loading , he clicks on an image. then this will cause the image to be displayed seperately inside a new windows and not inside the jQuery slider. while if he wait till the page fully loaded then there will not be any problem.
what i can not understand is that i am referencing all the scripts before rendering the page body. so this mean that the image gallery should not be available in the browser unless all the scripts are being fully loaded, but this is not the case.
here is how my _layout view looks like, where i am referencing all the scripts before the Renderbody():-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="~/img/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="~/img/favicon.ico" type="image/x-icon" />
<meta name="format-detection" content="telephone=no" />
<meta name="description" content="Your description">
<meta name="keywords" content="Your keywords">
<meta name="author" content="">
<title>#ViewBag.Title </title>
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/Customcss")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</head>
<body>
<!--==============================header=================================-->
<!-- <div class="container body-content">-->
#RenderBody()
and here is the view that is causing the problem :-
<header id="header" class="headerpages">
<div class="bgpattern"></div>
#Html.Partial("~/Views/Shared/Navigation.cshtml")
</header>
<div id="content">
<!--==============================row7=================================-->
<div class="row_7">
<div class="container">
<h2 style="text-align:center" >Project</h2>
<br/>
<div class="row">
<h2 class="padbot1">
Villa
</h2>
<ul class="listgall">
<li class="col-lg-4 col-md-4 col-sm-6 col-xs-6 colgal customBoarder">
<h5 class="customh5">Villa</h5>
<figure><img src="~/img/T/a.jpg" alt=""><span><strong>Project name:</strong><em>Villa</em><img src="~/img/T/searchsmall.png" alt=""></span>Read More about this vella<br /> </figure>
</li>
</ul>
<hr style="border-width: 3px 0 0;"/>
<h2 class="padbot1">
Triplex</h2>
<ul class="listgall">
<li class="col-lg-4 col-md-4 col-sm-6 col-xs-6 colgal customBoarder">
<h5 class="customh5">The TROJANA (Macedonian Oak) Triplex</h5>
<figure><img src="~/img/T/trojana.jpg" alt=""><span><strong>Project name:</strong><em>The TROJANA (Macedonian Oak) Triplex</em><img src="~/img/T/searchsmall.png" alt=""></span>Read More</figure>
</li>
</ul>
<hr style="border-width: 3px 0 0;" />
#Html.Partial("~/Views/Shared/_table.cshtml")
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 gmap">
<div class="map">
<iframe src="https://www.google.com/maps/embed/v1/place?key=A...."></iframe></div>
</div>
</div>
</div>
</div>
</div>
#section scripts {
<script>
$(window).load(function () {
//form1
$('#form1').sForm({
ownerEmail: '#',
sitename: 'sitename.link'
})
//thumb
// Initialize the gallery
$('.thumb').touchTouch();
});
</script>
<style>
#prevArrow, #nextArrow {
display: none;
}
</style>
so can anyone adivce how to fix this problem ? and why the image gallery will be available in the browser while the browsers is still loading the scripts ???
I know this problem has been solved but for the people who visit here, in case anyone else runs into the same problem and find it here.
As https://stackoverflow.com/users/575199/malk commented
use
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready");
});
instead of
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
alert("window is loaded");
});
The code below prevents the user from clicking the document(images or anything else) until the page is fully loaded. Add $(document).click(false); to $(document).ready function and $(document).click(true) to $(window).load function.
$(document).ready(function() {
$(document).click(false);
});
$(window).load( function(){
$(document).click(true);
});

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';

how to load an external html file that contains scripts

Unfortunately, I am not sure to understand anything to java, jquery and all this kind of thing. Nevertheless, I am trying to get some inspiration on forums in order to make a personal website that contains a vertical navbar and a div container in which external html pages will be loaded. Each html file uses an html5 applet called JSmol, which plots 3D molecules that can be manipulated interactively. The main page looks like this:
<!DOCTYPE html>
<html>
<head>
<title> 3D Chemistry </title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="Chem3D-CSS/MolChem.css" />
<link href='http://fonts.googleapis.com/css?family=Archivo+Narrow' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<!-- META TAGS start -->
<meta name="Title" content="Molecular Chemistry" />
<meta charset="UTF-8">
<!-- META TAGS end -->
<script type="text/javascript">
$(document).ready(function() {
// select all the links with class="lnk", when one of them is clicked, get its "href" value
// load the content from that URL and check the "status" of the request
// place the response or an error message into the tag with id="content"
$('a.lnk').click(function() {
var url = $(this).attr('href');
$('#content').load(url, function(response, status, xhr) {
// check the status, if "success", place the response into #content
// else, if "error", define an error message and insert it into #content
// else, display an Alert with the status
if(status=='success') {
$('#content').html(response);
}
else if(status=='error') {
var ermsg = '<i>There was an error: '+ xhr.status+ ' '+ xhr.statusText+ '</i>';
$('#content').html(ermsg);
}
else { alert(status); }
});
return false;
})
});
</script>
</head>
<body class="s_page" alink="#ee0000" link="#0000ee" vlink="#551a8b">
<div id="header"> <a id="UPS-link" href="http://www.univ-tlse3.fr/" title="Paul Sabatier University - Toulouse III">
<img src="Chem3D-IMAGES/UT3_PRES_logoQ.png" alt="Paul Sabatier University" id="logoUPS" width=300px />
</a>
</div>
<div id="vmenu">
<ul>
<li>Home</li>
<li>3D Molecules
<ul>
<li>Mol1</li>
<li>Mol2</li>
</ul>
</li>
<li>Symmetry
<ul>
<li>Symmetry Elements
<ul>
<li>C<sub>2</sub>H<sub>6</sub></li>
<li>Ru<sub>4</sub>H<sub>4</sub>(CO)<sub>12</sub></li>
</ul>
</li>
<li>Point Groups
</li>
</ul>
</li>
<li>Solids
<ul>
<li>fcc</li>
<li>hcp</li>
</ul>
</li>
</ul>
</div>
<div id="content">
</div>
<div class="s_author" id="footer">
author: romuald.poteau_at_univ-tlse3.fr
<br/>last modification: 2013/12/16
</div>
</body>
</html>
Up to now, I have worked on the PG.html file (Point Group entry in the vertical menu), which works perfectly fine when it is loaded separately. But is not the case when it is loaded inside the main page as an external html page. The title is the only thing that appears, it seems that the jsmol application is not properly initialized. May be this is specific to the invocation of jsmol ; or is this a general issue when one wants to load hmtl files with embedded scripts ?
<!DOCTYPE html>
<html>
<head>
<title> POINT GROUPS </title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="Chem3D-CSS/MolChem.css" />
<!-- META TAGS start -->
<meta name="Title" content="Molecular Chemistry" />
<meta name="Format" content="text/html" />
<meta name="Language" content="en" />
<meta charset="UTF-8">
<!-- META TAGS end -->
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="./JSmol.min.js"></script>
<script type="text/javascript">
// ---------------------------------------------------------------------------------
////// every page will need one variable and one Info object for each applet object
var Info = {
width: 500,
height: 500,
color: "0xC0C0C0",
use: "HTML5",
jarPath: "java",
j2sPath: "j2s",
jarFile: "JmolApplet.jar",
isSigned: false,
addSelectionOptions: false,
serverURL: "php/jsmol.php",
readyFunction: jmol_isReady,
console: "jmol_infodiv",
disableInitialConsole: true,
debug: false,
}
</script>
</head>
<body class="s_page" alink="#ee0000" link="#0000ee" vlink="#551a8b">
<div class="s_title" id="titlePG">
Point Groups
</div>
<div class="s_normal" id="mainPG">
<table border="0">
<tbody>
<tr valign="top">
<td nowrap="nowrap">
<script type="text/javascript">
Jmol.getApplet("Jmol1", Info);
Jmol.script(Jmol1,'load Chem3D-data/nh2cl.xyz;');
Jmol.resizeApplet(Jmol1, 500);
</script>
<br>
</td>
<td>
<script>
Jmol.setButtonCss(null,"style='width:300px'")
Jmol.jmolButton(Jmol1,"load Chem3D-data/nh2cl.xyz;", "NH2Cl (Cs)");
Jmol.jmolBr();
Jmol.jmolButton(Jmol1,"load Chem3D-data/cis-dichloroethylene.xyz;", "cis-dichloroethylene (C2v)");
Jmol.jmolBr();
Jmol.jmolButton(Jmol1,"load Chem3D-data/trans-dichloroethylene.xyz;", "trans-dichloroethylene (C2h)");
</script>
<br>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
I have tried to find an answer to this question by checking previous posts, but my poor skills do not allow me to identify relevant suggestions for such issue.
Thanks for any help.
// Create a DOM object from a URL
$html = file_get_html('http://www.google.com/');
// Create a DOM object from a HTML file
$html = file_get_html('test.htm');

Categories

Resources