-2

I've working on something where I need to put the JS variables in a separate JS file (just in one HTML file for now). I want all the variables' text to be in JS instead of just putting them in jQuery. Here's what I have so far:

<!DOCTYPE HTML>
<html>
<head>
    <title> </title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        var tempTitle = "Title";
        var tempNavTitle = "Nav Title";
    </script>
    <script>
        $("title").html(tempTitle);
        $(".nav > .nav-id > .nav-title").html(tempNavTitle);
    </script>
</head>
<body>
    <div class="nav">
        <div class="nav-id">
            <div class="nav-title"> </div>
        </div>
    </div>
</body>

As you can see, I've already got the title part working, but the HTML part isn't working (and that's my issue).

  • JQuery ***is*** JavaScript. A variable created by one is available by the other as long as the scope of the variable is correct. – Scott Marcus Nov 28 '17 at 22:20
  • 1
    your problem is that the script runs before elements exist ... if only there was a way to wait for the `$(document)` to become `.ready` – Jaromanda X Nov 28 '17 at 22:21
  • You could end up having too much variables in global scope. I would suggest having one object with those variables. – user8672473 Nov 28 '17 at 22:28

1 Answers1

0

You don't separate plain JavaScript from JQUery. They are both JavaScript. As long as a variable is in scope, you can access it.

// When the document's HTML is fully parsed, run the function
// passed to JQuery:
$(function(){
  var tempTitle = "Title";
  var tempNavTitle = "Nav Title";
  
  // Use .text(), not .html() when setting/getting non-HTML strings
  $("title").text(tempTitle);
  $(".nav > .nav-id > .nav-title").text(tempNavTitle);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
  <div class="nav-id">
    <div class="nav-title"> </div>
  </div>
</div>
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54