use jQuery to pass a parameter to the div that I have loaded

I have multiple html pages that all have the same navigation bar. To simplify things, I created a single html file called topnav.html and then used jQuery to load it into each page.

javascript

<script type="text/javascript">
$(function() {        
    $('#topnav').load('topnav.html');
});
</script>

html

<body>
<div id="topnav"></div>
...

However, now I realize that each page needs to have unique properties, such as different titles. How can I pass a title parameter to the topnav.html page?

Answer №1

The initial solution provided is in PHP because it is my preferred language. However, if you prefer to use JS, refer to the revised version below.

When working with PHP, you have the option to include a file containing functions and pass those functions as parameters:

index.php

<?php
    include "topnav.php";
    top("title");
?>

topnav.php

<?php
    function top($title) {
?>
    <div id="topNav">
        <!-- Additional code here -->
        <span id="title"><?= $title ?></span> <!-- Insert title here -->
    </div>
<?php
    }
?>

In my website development, I refrain from utilizing JS/jQuery to load page resources. Instead, I find PHP's include() function more practical and hence use it extensively!


UPDATE

Upon reflection, implementing a similar approach in JavaScript is feasible albeit slightly more intricate. By defining a function in JS, you can invoke it directly within the page:

index.html

<script type="text/javascript">
    $(function() {        
        $('#topnav').load('topnav.html');
        $("body").append(top("title"));
    });
</script>

topnav.html

<script>
    // return or print out resource string
    function top(title) {
        return "<div id='topNav'>" +
                   "<!-- Additional code here -->" +
                   "<span id='title'>" + title + "</span>" +
                "</div>";
    }
</script>

UPDATE 2: In-depth explanation (as per request)

The JS example loads the resource file similarly to your method. However, instead of a plain HTML file, it involves a JS file. Once loaded, you are able to utilize the JS script. The additional script essentially allows for the utilization of a mostly predefined string, with the flexibility to incorporate variables (e.g.,

"<span id='title'>" + title + "</span>"
enables insertion of title).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Convert all relative path URLs in images to absolute paths using either PHP, javascript, or jQuery

I am looking to transform any relative URL found on a webpage, with the main intention of resolving issues related to images not being displayed. The goal is to convert these relative URLs into absolute URLs. For example: From <img src="/folder/folder ...

Eliminate the tiny space between the top of the webpage and the navigation bar

I've made several attempts to eliminate the gap between the navigation and the top by setting margin: 0; and border-box in various places to no avail. Strangely, I couldn't get the navigation bar to stick, so I had to resort to making the header ...

Vue.js table columns not displaying properly when using Hide/Show checkboxes

Recently, I developed a vue.js bootstrap table to load data from local JSON files. My current challenge is implementing show/hide columns using checkboxes. While I have solved most of the issue, there's one lingering problem: when I hide a column and ...

How can I trigger a function again when an anchor link is clicked and received via Ajax?

I am currently working on creating a unique page transition effect using jQuery and Ajax. This is what I have so far: $(".transitionLink").on("click", function (event) { event.preventDefault(); var href = $(this).attr("href"); window.histor ...

Encountering an error in React js where it is unable to read property "0" when making an API call

I am facing an issue with accessing data from the fetch function in my project. The goal is to pass the data from the action to the reducer. The API is being called using a fetch function, which returns a promise. So, the API call is made separately and th ...

What is the process for altering the image on a jQuery mobile a href button?

Is it possible to use a custom image instead of a normal rectangular shape for a jquery mobile button? I'm looking for references on how to do this. The code below is an example of what I want. Here is an example of a normal button: <a data-role= ...

Arrange the array neatly within a textarea

Is there a way to print an array into a textarea and insert a line break or separator after every 4th row in the array or textarea? For instance, I have some input fields within a form that need to be displayed in a textarea before submission. This is nec ...

jQuery is being loaded upon page load

I'm facing an issue with the following script: function manualSeat(){ $('.dimmed').show(); $("#petaKursi").load('url'); $('#wagonCode').val(''); $('#wagonNumber').val(''); ...

Symbol placed atop text within a navigation bar

I am in the process of creating a custom menu for my website. I want to include an icon with text underneath, but when I add the text it shifts to the right and messes up the alignment. Menu with Icon Only Menu with Text (causes alignment issues) @impo ...

What is the best way to retrieve all form input values by utilizing the blur event within the `addEventListener` method

I'm currently attempting to retrieve form values dynamically using addEventListener, but I'm only able to access the first input field and not the others. Below is my current code snippet: $(document).ready( function() { const user_inpu ...

Host app is failing to render shared components in SSR

Encountering an issue while implementing SSR with module federation? Check out my code example Steps to Begin: Run yarn install:all command Execute yarn shell:server:build task Start the server using yarn shell:server:start Initiate remote services with y ...

Having trouble populating the input text field with the selected value from a dropdown using JavaScript

I have implemented a JavaScript function to retrieve the id of a dropdown select with id='odrid'. The script looks like this: $('#odrid').change(function(){ $.getJSON( 'fetch.php', 'odrid='+$(&ap ...

Error message received when calling a function within a Vue watcher states "function is not defined"

My goal is to trigger a function in a Vue component when a prop changes using a watcher: props: [ 'mediaUrl' ], watch: { mediaUrl: function() { this.attemptToLoadImage(); } }, medthods: { attemptToLoadImage: function() { console ...

What is the recommended value for the auto-incremented ID field when using the POST method in Node.js?

Currently, I am utilizing the mysql package for NodeJs in order to Post Data to a MySqlDB. Below is an example of my code: app.post('/countries', (req, res) => { const country = req.body.country; const city = req.body.city; const t ...

The ASP.NET Core MVC controller encounters a null input parameter when called by an ajax request

Here is the scenario involving an ajax call: ... $("#testBtn").click(function (e) { e.preventDefault(); $.ajax({ url: "/profile/GuestList", data: {"keytype": "1"}, method: "POST&q ...

How to split a string in JavaScript using white space

I'm looking to separate a string while preserving white space, for example: var str = "my car is red"; var stringArray []; stringArray [0] = "my"; stringArray [1] = " "; stringArray [2] = "car"; stringArray [3] = " "; stringArray [4] = "is"; string ...

Displaying gratitude message using AJAX and executing PHP script

I've created a form where I want the "thank you" message to be displayed after submission and also run a PHP script to insert data into the database. However, currently, although the values are being passed correctly via the URL, the upis.php script i ...

Array indexes can be negative

My approach to storing objects for a grid involves using a two-dimensional array. In this case, the grid is hexagonal, making it more convenient to utilize a coordinate system centered at (0, 0) and ranging from -r to r. The following source suggests that ...

Is there a javascript function that performs the reverse action of indexof()?

Is there a JavaScript function that is the opposite of indexOf()? In my code, when you press the button it will display 3 [from indexOf(".")]. However, I am looking for a function that is the opposite of indexOf(), which would show me 2 [decimal]. http: ...

Ways to incorporate validation into Material-UI form input fields

I have a react functional component that utilizes Material UI form, which includes TextField. The onChange event is managed in the "Container Component". I have added required for client-side form validation, but it doesn't seem to be working. Do I ne ...