Steps for embedding a webpage within a div element

I am facing an issue while trying to load a web page within a div using an ajax call. Unfortunately, it's not working as expected and displaying the following error message:

jquery.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience

Can anyone provide guidance on resolving this problem?

<div class="warper">
    <div class="menu">
        <a href="#" data-target="home">Home</a>
        <a href="#" data-target="pageOne">Page One</a>
        <a href="#" data-target="pageTwo"> Page Two</a>
        <a href="#" data-target="pageThree">Page Three</a>
    </div>



  <div id="content"></div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
    $(document).ready(function () {

        $("#content").load('home.html');
        // Set trigger and container variables
        var trigger = $('.menu a'),
            container = $('#content');

        // Fire on click
        trigger.on('click', function () {
            // Set $this for re-use. Set target from data attribute
            var $this = $(this),
                target = $this.data('target');

            // Load target page into container
            container.load(target + '.html');

            // Stop normal link behavior
            return false;
        });
    });
</script>

Answer №1

To clarify, the goal here is to insert content into a div, not an entire webpage. A webpage would have its own document and DOM, requiring an <iframe>.

Your issue may stem from using .data() instead of .attr(). In my solution, I utilize vanilla JavaScript's .getAttribute(), which achieves the same result without needing an additional jQuery call. Essentially, your code appears to be attempting to:

container.load(undefined + '.html');

I personally have not used the load method in this manner (the fact that it was overloaded for both event handling and ajax surprises me). A possible implementation could resemble the following example:

<script>
  $('#content').load('home.html');

  $('.menu').on('click', 'a', function (e) {
    e.preventDefault(); //prevent normal link behavior

    $('#content').load(this.getAttribute('data-target') + '.html');
  });
</script>

Furthermore, if your script resides at the bottom of the <body>, there is no need for $(document).ready(), as the code will only execute once the document has finished loading.

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

Explore the Wikipedia API to retrieve a random page along with its associated links

Is there a way to generate a random page using the code generator=random? Unfortunately, it doesn't seem to work with my current code snippet: http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&page=Little_Richard&ca ...

Merging Data with mongoDB

Just starting out with MongoDB, I have developed an app that functions similar to Twitter with followers and following. Here is the schema I am working with: UserSchema : username:'Alex', pass:'salted', likes:'200&ap ...

Selenium - Struggling to locate elements that are undeniably present on the website

I started a fun side project to automate tasks on the website using Selenium to automatically complete all achievements. You can check out my code on GitHub: https://github.com/jasperan/pyfastfingers However, I've run into an issue with the login pa ...

Tips for Handling JQuery .get() Response

After coming across a helpful suggestion on manipulating AJAX response data with jQuery from this website, I attempted to apply it to my own project. Unfortunately, despite trying to make changes to the object using a jQuery .get() method, I found myself u ...

When using addClass("test"), it throws an error message: TypeError: undefined is not a function

Upon examination in the console, I discovered the following: $(".myCssClass")[0].parentNode <li><span class="myCssClass">some text</span></li> I am attempting to add a CSS class to the parent span tag within the <li> element ...

How can I use JQuery to sum up the numbers within div elements?

Is there a way to automatically number the generated blocks? For example, the first block would display "1", the second "2" and so on. Below is my current code. Simply input the desired number of blocks in the input field. <!DOCTYPE html> <html ...

A convenient method for converting horizontal columns into vertical columns on mobile screens without using <div> tags or setting a minimum width, perfect for email formatting

After experimenting with using <div> elements and applying a min-width attribute to an email, I have come to the conclusion that these methods do not yield satisfactory results. While the alignment of horizontal columns works well on desktop screens, ...

Determining the dimensions of a div once it has completed loading

Is there a way to retrieve the width and height of a div after it has fully loaded, rather than before? I am currently using JavaScript to get the dimensions, but it seems to be returning the values before the image has finished loading. How can I rectify ...

Travis is checking to see if the undefined value is being

My experience with jasmine testing has been successful when done locally. However, I am encountering issues on Travis CI where all the API tests are returning undefined values. Here is an example: 4) Checking Server Status for GET /api/v1/orders - Expecte ...

My CSS disappears when using an ASP.Net MVC form

Unable to find any similar issue on Google... seeking some assistance. When I apply CSS formatting to style my form as desired, it displays correctly on the page without any issues. However... When I place the actual form within the following code snipp ...

How to Properly Implement app.use() in Express for Middleware

What is the reason behind some middleware functions being passed in with invocation parentheses, while an anonymous function is passed in without being invoked? app.use(logger()); app.use(bodyParser()); If logger() is evaluated immediately and the return ...

Error: SvelteKit server-side rendering encountered a TypeError when trying to fetch data. Unfortunately, Express is not providing a clear TypeScript stack trace

I've been monitoring the logs of the SvelteKit SSR server using adapter-node. After customizing the server.js to utilize Express instead of Polka, I noticed some errors occurring, particularly when the fetch() function attempts to retrieve data from ...

Acquiring row data upon checkbox selection: A step-by-step guide

I'm struggling to separate and assign the values returned by a function to different parameters. function saveTaxes() { $('input[type=checkbox]').each(function() { if ($(this).is(':checked')) { //test console.log ...

Incorrect outcome when utilizing ajax to update a div within a for each loop

For a while now, I've been facing an issue with a div and form within a forEach loop. When one of the forms in the loop is submitted, the content inside the corresponding div is updated in the database and refreshed using JavaScript and Ajax. The upda ...

Creating a multilingual website with Nextjs 13 App Router using internalization, all without the need

As I develop a web app that requires user authentication to access, I am currently using Next.js 13 with the App Route (not Pages Route). My goal is to implement internationalization without having to create sub-routes like /en, or use domains such as mywe ...

Popup to confirm JqGrid inline editing

While I am working on inline editing with jqgrid, the client has requested a confirmation dialog to appear when saving changes, similar to how delete operates. Upon reviewing http://github.com/tonytomov/jqGrid/blob/master/js/grid.inlinedit.js, it is eviden ...

Tips for utilizing the if-else directive in an AngularJS controller

My current challenge involves HTML coding. <li><strong>Scrub:</strong> {{insuredProfile.permanentAddress.isScrubbed}}</li> This code displays either true or false. I want to show Yes for true and No for false. Using data-ng-if, ...

How to assign attributes to all child elements in Angular?

I have a unique component in Angular that I utilize throughout my app. It's a button component which I use by calling <app-delete-btn></app-delete-btn> wherever needed. I tried to set the tabindex="1" attribute for my component ...

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

Exploring the differences between the meta viewport and font size

My website includes the following code in the section: <meta name="viewport" content="width=990"/> This setting helps to display my webpage well on mobile devices, as using width=device-width causes issues with elements that have 100% width. Howeve ...