Wordpress: how to use javascript variables into html body - javascript

I'm really new in Wordpress, Javascript and HTML so I know this question is really basic, but I wasn't able to find it solved anywhere.
I want to create some variables in javascript and then display them in my page which is created in Wordpress.
Reading other posts I've found I need to insert a javascript code that at the end stores my variable this way (dummy version):
<script type="javascript">
document.getElementById('test').innerHTML = 'hello';
</script>
And then on the text block I want to display my variable to be displayed I should add this code:
<body>
<p id="test"></p>
</body>
However I've tried adding the javascript in the header (Tatsu header) and also tried adding it in the text block (HTML version) in different combinations and it never worked. Tried adding the script block before and after the body block, and also tried having it inside, before and after the display line.
If I try the following it works:
<body>
<p>hello</p>
</body>
So I guess my problem is that I'm not setting the variable properly.
Can anyone help? Apologies if this is already solved somewhere, spent some hours and wasn't able to find it.
Thank you in advance.

Your problem is the type of which you're using here:
<script type="javascript">
I noticed this whilst constructing an example of this problem.
javascript is not a correct mime type.
It should be text/javascript as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Please note this is not a complete list. Such as application/javascript also being valid. Please also see https://www.iana.org/assignments/media-types/media-types.xhtml
Working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p id="test">
This shouldn't show up
</p>
<script type="text/javascript">
console.log("####### JAVASCRIPT IS RUNNING ######")
document.getElementById('test').innerHTML = 'hello';
</script>
</body>
</html>

Related

6 javascript tasks assigned to me by my lecturer

I am a complete beginner to javascript. I am also new to this website. I am asking for help to complete an assignment. I have been trying for more than 4 hours by looking at lecture material and online for a solution. It is causing me a lot of unnecessary stress. Before javascript we only used CSS and Html. I was given 6 javascript tasks to manipulate the html file (taskc.html) already given to me.
The tasks are as follows
Make a statement to change contents of h1 from "Welcome" to "Text"
2nd statement should make an new alert window when the page loads that delivers a message explaining what the page is about
3rd statement should change the title to "text"
4th statement should log the contents (innerHTML) of the first paragraph element in the console.
5th statement should hide the contents of the second paragraph when the page loads
6th statement should change the contents of the header to have a new colour of your choice
Here is that html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
</body>
</html>
Because the actual coding im meant to add is meant to be in the .js file I was given. so I figured I had to link the js file in the html file so I added
<script type="text/javascript" src="taskc.js"></script>
With that out of the way I went to the lecture notes and I thought I would simply need to modify some of the code given to me there like
document.getElementById('demo').innerHTML = 'Hello World!';
When I put this code in brackets I got the error (document is not defined)
I modified it to match the requirements for task 1
here it is
document.getElementById('header').innerHTML = 'text';
I was confused because I didn't know what this error meant and of course Errors and how to fix them are never explained so I had to lookup how to resolve the error.
I found that to fix it I have to declare it as a variable so I ended up doing this.
var document = 'taskc.html';
When I did this for document, alert and console all the errors went away, but when I did a live preview only statement 1 was working
If anyone could help me fix this I would really appreciate because I don't understand enough javascript to be able to complete this in a reasonable amount of time.
So first: Please use Javascript functions to keep your code tidy and clean.
Example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
<script type="text/javascript" src="taskc.js">test();</script>
</body>
</html>
function test(){
alert("This is a test!");
}
Always implement scripts that are document referenced at the bottom of your html.
If you use JQuery you can use following code to check document is loaded:
$(document).ready(function(){
//foo bar
});

linking JavaScript to HTML file

I am at my wits end with linking a javaScript file to my main.html, they are both in the same folder.
I have viewed multiple Stack overflow topics regarding this question, and for some reason none of the solutions solve my answer.
My current code is what I have below:
[main.html]
<!DOCTYPE html>
<head>
<link rel="javascript" href="jsfile.js">
<title>JavaScript</title>
</head>
<body>
<div class="Header">
<h1>JS Basics</h1>
</div>
</body>
[jsfile.js]
document.write("Hello World");
This code does not display the "Hello World" message, however if i insert the code directly into the HTML file it does.
I appreciate any and all help on this matter.
Add like following not with link.
<script type="text/javascript" src="jsfile.js"></script>
Just type:
<script src="yourJavascriptFilename.js"></script>
Most importantly add this line to the bottom of your body tag to avoid your browsing requesting JavaScript to be loaded before displaying your HTML.
You're using the incorrect link for JavaScript.
Try using this instead
<script src="jsfile.js"></script>

Google Trends embed is destroying my webpage

I am doing my damnedest to embed a Google trends chart into a section of my site.
In theory, it seems easy:
1.) copy script from Google:
2.) Clear a space in your webpage:
3.) Add the code:
<div class="full-row4" style="height: 300px;">
<script type="text/javascript" src="https://ssl.gstatic.com/trends_nrtr/1386_RC02/embed_loader.js"></script>
<script type="text/javascript">
trends.embed.renderExploreWidget("TIMESERIES", {"comparisonItem":[{"keyword":"/m/078rys","geo":"","time":"today 12-m"}],"category":0,"property":""},
{"exploreQuery":"q=%2Fm%2F078rys&date=today 12-m","guestPath":"https://trends.google.com:443/trends/embed/"}
);
</script>
</div>
Seems easy right? wrong!
Every time I do this, I get this result:
Upon further inspection, I found that when those scripts were loaded in, it wipes my entire body of the webpage. (Note: the chart gets loaded in thru an AJAX call containing the entire active page minus the navbars)
I've tried an array of different logic to try and get this to work, but everything I try deletes all HTML in the body tag of the webpage. (script tags are still there)
I found people with a similar issue, but it seems Google has changed how you embed these widgets into a site. Rendering any previous stackoverflow documentation useless. (at least from what I found)
you can use renderExploreWidgetTo() function instead, it takes DOM element as first parameter:
var divElem = document.getElementById('wrapper');
trends.embed.renderExploreWidgetTo(divElem,"TIMESERIES", {"comparisonItem":[{"keyword":"dbs bank","geo":"","time":"today 12-m"}],"category":0,"property":""}, {"exploreQuery":"q=dbs%20bank&date=today 12-m","guestPath":"https://trends.google.com:443/trends/embed/"});
Google trends embed script create an iframe at the hosting website.
Here is a simple example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>hello</h1>
<div>
<script type="text/javascript" src="https://ssl.gstatic.com/trends_nrtr/1386_RC02/embed_loader.js"></script> <script type="text/javascript"> trends.embed.renderExploreWidget("TIMESERIES", {"comparisonItem":[{"keyword":"dogs","geo":"","time":"today 12-m"}],"category":0,"property":""}, {"exploreQuery":"q=dogs&date=today 12-m","guestPath":"https://trends.google.com:443/trends/embed/"}); </script>
</div>
<h1>world</h1>
</body>
</html>
As you can see, the body is not affected.
The problem is probably not with the trends scripts, but a more general issue.
Try creating an iframe at your page, does it display correctly?

Using jquery in js file

Okay so all I am trying to do is make the jquery work in my javascript file which is linked to a html file. I created a totally new file for this to test it. The whole contents of the html file are:
<!DOCTYPE html>
<html>
<script src="C:\Users\Me\Desktop\Programming\jquery-1.12.4" type="text/javascript"></script>
<script src="check.js"></script>
<head> <h1>test</h1>
</head>
<body>
</body>
</html>
And the whole content of the js file is
$("h1").css("color", "red");
But when I open the html file in chrome the change I put in the js file with jquery doesn't show up (e.g the heading is not red). I just want to figure out how to make it so that it does.
EDIT:
Thanks for the help everybody, I was able to make it work :)
did you try this?
$(document).ready(function(){
$("h1").css("color", "red");
});
not sure but, does your browser access local files directly? im pretty sure that browser sandbox gonna reject that, maybe cors plugin on chrome?
EDIT:
try importing this instead...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Move your <h1> tag to be in the <body>
Move your <script> tags to the <head>
Replace your code in your JS file with what imvain2 said, so
that the JS will load once your document is ready.
Make sure you are correctly referencing your jQuery script. You can even use this to test it out:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Try to use jQuery CDN, this way you don't need to worry if jQuery loaded correctly or not.
$(document).ready(function() {
$("h1").css("color", "red");
});
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="check.js"></script>
<head></head>
<body>
<h1>test</h1>
</body>
</html>
There are a couple issue as described in other posts. All your meta, script, css references, etc. should go int the <head> and never header tags. Also need to correctly reference your javascript files.
<head>
</head>
<body>
<header>
<h1>test</h1>
</header>
</body>
Example: JSFiddle
If you want to use jquery in .js file all you need to do is type: src=" ..." above code.

Missing } in XML Expression

I am trying to change our site to load a Header through jquery using the .load() function but to do so I need to set the Title of the page.
From another StackFlow question it was suggested to do something as simple as
$(document).ready(function() {
document.title ='Name Changed to Protect the Innocent';
});
When i do this I get the firebug error
Missing } in XML Expression for that line in the script
I am sure there is probably an easy solution but it is certainly escaping me.
I've just tested this out here, please see if you have created your html document in the same way. Code as below.
<html>
<head>
<title>Old Title</title>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
document.title ='Name Changed to Protect the Innocent';
});
</script>
</body>
</html>
I found what the problem was. This script was in the middle of another script block which was causing the error.
Thanks for all the help.

Categories