Getting elements from multiple html pages into javascript - javascript

I have two html pages called home.html and about.html.
And I also have a js file called main.js which is linked with both of the html pages.I have a div with a class of "home" in home.html and another div with a class of "about" in about.html. Class "home" has a text and class "about" has a text too.Now I slected them in my main.js file like this,
const home = document.querySelector('.home')
const about = document.querySelector('.about')
And manipulated them like this,
home.style.color = 'red'
about.style.color = 'green'
But the problem is only the variable 'home' is changing its color not the variable
'about'
I think there is maybe a particular way to select elements from multiple pages.
But if there is pls let me know bcz the variable 'about' is not getting manipulated with anything.
const home = document.querySelector('.home')
const about = document.querySelector('.about')
// Manipulated them like this
home.style.color = 'red'
about.style.color = 'green'
<!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">
<title>ES8 Project</title>
<link rel="stylesheet" href="main.css" /> </head>
<body>
<div class="home"> HOME </div>
<script src="main.js"></script>
</body>
</html>

Rather than:
<div class="home"> HOME </div>
<div class="about"> ABOUT </div>
You can use a custom data attribute like data-page:
<div data-page="home"> HOME </div>
<div data-page="about"> ABOUT </div>
Then, if you want to do something more dynamic than straightforward CSS styling, you can script the following:
const myDiv = document.querySelector('[data-page]');
switch (myDiv.dataset.page) {
case ('home') : [... DO SOMETHING... ] ; break;
case ('about') : [... DO SOMETHING... ] ; break;
}
N.B. When using this setup, where you do only want to apply CSS styling, then definitely use CSS:
[data-page="home"] {
color: red;
}
[data-page="about"] {
color: green;
}
Further Reading:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

Related

can you add src and play in js and html

This is not working for me. I created script src to my HTML
function eyob1() {
var play1 = document.getElementById("aud").src="eyobmknn/trk1.mp3"
play1.loop = "true";
pley1.play();
}
<!DOCTYPE html>
<html >
<head >
<link rel="stylesheet" href="launch.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div onclick="openeyob();" class="eyob" id="eyob">Eyob Mekonnen</div>
<div id="container">
<div onclick="eyob1();" class="eyob1" id="eyob">01 track 01
<script src="lunch.js"></script>
</body>
</html>
and I can add src but the sound cannot be played
I answared a similar question here: How to play audio loaded via file input
It's possible to change the src attribute using the method SetAtrribute:
function eyob1() {
var play1 = document.getElementById("aud")
play1.settAtribute('src', "eyobmknn/trk1.mp3")
}
But is important to notice that your code does't have a an element with id='audio'. Your script won't work as it is now.
A good start point is here: https://developer.mozilla.org/en-US/docs/Web/Tutorials

Iframe: White screen after setting document.location 2x

I'm creating a web application that I aim to embed into my Wix site.
The web application that I need can basically be reduced into a text screen & a button to change the screen view/page (the html that is displayed).
However, the problem is that independent on whether I start from the "home page" or from the "page page", the application loads two next screens and gives me a white screen after.
I've also tried other options for changing the url - ie location.href, window.location and such, and even tried changing the page via <a href= URL , yet the problem persists.
Below is a simplification of my code:
Page HTML
<!DOCTYPE html>
<html>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<head>
<base target="_self">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body>
<h1>page page</h1>
<button id="pagebtn" class="font-family: Raleway; font-size: 16px; waves-effect waves-light btn-small blue accent-2"><i class="material-icons left">check</i> Navigate to home </button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
document.getElementById("pagebtn").addEventListener("click",changepage);
function changepage(){
var url_new = "https://script.google.com/macros/s/AKfycbzKN9vYBa1yQguooTnijIipyMdAMbXo7a61wjWHt0ybCynH2bxj/exec?v=home";
document.location = url_new;
}
</script>
</body>
</html>
Home HTML
<!DOCTYPE html>
<html>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<head>
<base target="_self">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body>
<h1>home page</h1>
<button id="homebtn" class="font-family: Raleway; font-size: 16px; waves-effect waves-light btn-small blue accent-2"><i class="material-icons left">check</i> Navigate to page </button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
document.getElementById("homebtn").addEventListener("click",changepage);
function changepage(){
var url_new = "https://script.google.com/macros/s/AKfycbzKN9vYBa1yQguooTnijIipyMdAMbXo7a61wjWHt0ybCynH2bxj/exec?v=page";
document.location = url_new;
}
</script>
</body>
</html>
JS Code // Code.gs
var Route = {};
Route.path = function(route, callback) {
Route[route] = callback;
}
function doGet(event) { //<!-- Not visible to the user, serverside -->
Route.path("page", loadPage);
Route.path("home", loadHome);
if (Route[event.parameters.v]) {
return Route[event.parameters.v]();
} else {
return HtmlService.createTemplateFromFile("home").evaluate();
}
Logger.log("do get1 " + event.parameters.v);
}
function loadPage() { //<!-- Not visible to the user, serverside -->
var tmp = HtmlService.createTemplateFromFile("page");
return tmp.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function loadHome() { //<!-- Not visible to the user, serverside -->
var tmp = HtmlService.createTemplateFromFile("home");
return tmp.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
The links in the code are for redirecting to a different url "view".
Thanks!
//Edit:
Unfortunately still without a solution nor an understanding of the underlying cause of this problem. By simply testing around - I found that when using window.open the scripts works (however, it keeps opening new tabs/windows that is not desirable. As the URL of the site itself does not change - perhaps this is the underlying reason for this problem? (meaning that I should redo the router or input the url in a different way to actually change what is written)?
I resolved my issue by changing document.location to window.top.location
However, as I need to embed this inside of my website, it opens up a new window whenever (window.top after all), whenever clicking the "Navigate" buttons- it does not work as intended, but for a temporary fix it will do

How to add event with Javascript to an html tag

I've a landingpage with dynamic html tags.
The Problem is, that i can't select directly the tag. Its a link.
the following code is the construct:
<div id="testid"><div><div>Button 1<div><div><div>
Every time someone clicks on the link (a-tag) I want to fire an event like the following code:
Button 1
the question: what is the Javascript code to add the onclick="dataLayer.push({'event': 'button1-click'}) attribute to the a tag.
I tried the following code:
var d = document.getElementById("testid").firstchild;
d.setAttribute("onclick", "dataLayer.push({'event': 'button1-click'})");
but it seems to the code is incorrect. The a tag is also not the first child; there are 2 divs between :(
Use querySelector and addEventListener:
document.addEventListener('DOMContentLoaded', function () {
var dataLayer = [];
var d = document.querySelector("#testid a[name=button1]");
d.addEventListener("click", function () {
dataLayer.push({ 'event': 'button1-click' });
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="testid">
<div>
<div>
Button 1
<div>
<div>
<div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="script.js">
</script>
</body>
</html>
There's a few things you were missing from your JS.
Using a more specific selector (#testid a[name=button1] vs. the firstchild of #testid, which was not accurate).
Wrapping all the code in a DOMContentLoaded listener. JS that depends on elements on a page needs to wait for the page to build first, that's what DOMContentLoaded is.
Check out my solution. Hope this helps.
var d = document.querySelector("#testid a");
var dataLayer = []
d.onclick = function () {
dataLayer.push({'event': 'button1-click'})
console.log(dataLayer.length)
}
<div id="testid"><div><div>Button 1<div><div><div>

Navigation between pages - html

I trying to navigate between 3 pages which contain the same header and footer but each page has different content.
I want to load different contents html on hash change.
The problem is that when I click on the same page again, the content.html loaded again.
How can I use the content without loading the html again and again, using java script/html/jquery?
Code example:
Navigationbar.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Navigation Bar</title>
<link rel="stylesheet" type="text/css" href="css/navigationbar.css">
</head>
<body>
<nav>
<img id="navigation-bar-logo" class="logo" src='images/flybryceLogo.png'>
<ul class="navigation-bar-ul">
<li class="navigation-bar-li"><a id="navigation-bar-contact-page-tab" href="#contact.html">CONTACT</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-about-us-page-tab" href="#aboutus.html">ABOUT US</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-home-page-tab" href="#home.html">HOME</a></li>
</ul>
</nav>
</body>
</html>
initial.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>One Page Test</title>
<link rel="stylesheet" type="text/css" href="css/homepage.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="main-container" class="main-container">
<div id="header" class="header">
</div>
<div id="content" class="content"></div>
<div id="footer" class="bot"></div>
</div>
<script>
document.onreadystatechange = function(){
if (document.readyState == 'complete') {
window.onhashchange=hash_change;
window.onload=hash_change;
if(window.location.hash==''){
//default hash
window.location.replace('#home.html');
}
//load the header
$("#header").load("fragments/navigationbar.html");
//load the footer
$("#footer").load("fragments/footer.html");
}
}
function hash_change()
{
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
$("#content").load("home.html");
} else if (newHashCode === "aboutus.html") {
$("#content").load("aboutus.html");
} else if (newHashCode === "contact.html"){
$("#content").load("contact.html");
}
}
</script>
</body>
</html>
A longer but suitable solution would be to build a content cache on your own.
For example asking to the server just once the html and then setting it to the $('#content') element. You can use this helper function.
var contentsCache = {};
var getAndCache = function(url, callback) {
var cachedContents = contentsCache[url];
if (!cachedContents) {
$.get(url, function(serverContents) {
cachedContents = serverContents;
contentsCache[url] = cachedContents;
callback(cachedContents);
});
} else {
callback(cachedContents);
}
};
And then replace the $('#content').load calls by calls to this new asynchronous way.
function hash_change()
{
var fillContentCb = function(s) {
$('#content').html(s);
};
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
getAndCache("home.html", fillContentCb);
} else if (newHashCode === "aboutus.html") {
getAndCache("aboutus.html", fillContentCb);
} else if (newHashCode === "contact.html"){
getAndCache("content.html", fillContentCb);
}
}
As suggested in some comments, consider using native HTML navigation instead. Another suggestion is to use a client-side JS framework which supports routing if this application is likely to grow.
Add an if condition that checks whether the current hash location matches with the one that's been clicked on, and if it does just return. You'd have to store it in a global JS variable, and set it every time you navigate.

How can I change the html title of my main.hbs file from a partial.hbs?

I am trying to change my html title depending on the partial that I load for the body.
Parent html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
{{title}}
</title>
</head>
<body>
{{>body}}
</body>
</html>
Partial body.hbs file:
<h1 id="brick-mason">Brick Mason</h1>
<h3 id="what-is-a-brick-mason-">What is a brick mason?</h3>
<p>Brick masons use various stones, concrete and bricks to build walls, walkways, fences, and other structures.</p>
What can I change so that my partial can determine what the title on my main html page displays?
you can do it easily with JavaScript,
just add in the body.hbs :
<script> document.title = 'the title here ' </script>
What I ended up doing was including a second partial in the handlebars file and then splitting them out in the grunt file config.
gruntfile.js
file_context: function(src) {
var fileName = path.basename(src).split(".")[0];
var obj = glob.route[fileName];
var fileString = fs.readFileSync("./" + src, "utf8").split("<split />");
return {
partials: {
header: fileString[0] || "",
body: fileString[1] || "",
},
src: 'src/base.hbs',
dest: path.join('static', obj, 'index.html')
};
}
base.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/index.min.css" />
{{>header}}
</head>
<body>
<div id="nav_background"></div>
<div id="main">
<div id="nav_bar">
<div class="nav left_nav">
BlueCollarJobs101
</div>
<div class="nav right_nav">
States
Jobs
Contact Us
</div>
</div>
<div class="markdown-body">
{{>body}}
</div>
</div>
</body>
</html>
In your Partial.hbs body add the script to manipulate the tags
<h1 id="brick-mason">Brick Mason</h1>
<h3 id="what-is-a-brick-mason-">What is a brick mason?</h3>
<p>Brick masons use various stones, concrete and bricks to build walls, walkways, fences, and other structures.</p>
<script>
const title = document.querySelector('title');
title.innerHTML = 'Partial';
</script>

Categories

Resources