Tips for updating text in a freshly opened window using JQuery or JavaScript

I have a function that is triggered by a button click to open a new window or tab, display an alert, and update text. Here is the code snippet:

function nWin(p) {
    var setStyle = "<style rel='stylesheet'>\
        .vTop {\
            vertical-align: top;\
        }\
        <\/style>";
    var setScript = "<script>alert('test');<\/script>";
    setScript += "<script src='http://code.jquery.com/jquery-1.11.0.min.js'><\/script>";
    setScript += "<script>$(function () { $('#sText').html('UPDATED TEST'); });<\/script>";
    var w = window.open();
    var createBody = $(w.document.body);
    var createHead = $(w.document.head);
    createBody.html("");
    createBody.html(p);
    createBody.append("<span id='sText'>THIS IS A TEST</span>");
    createHead.html(setStyle);
    createHead.append(setScript);
}

However, when I click the button, the alert appears on the original page instead of the new window/tab, and the sText does not update as expected.

How do I fix this issue so that the alert shows in the new window/tab and the span text gets updated correctly?

Answer №1

If you want to change how you add content to a new window, try using the following method:

function createNewWindow(p) {
    var style = "<style rel='stylesheet'>\
        .vTop {\
            vertical-align: top;\
        }\
        <\/style>";
    var script = "<script>alert('test');<\/script>";
    script += "<script src='http://code.jquery.com/jquery-1.11.0.min.js'><\/script>";
    script += "<script>(function () { $('#sText').html('UPDATED TEST'); })();<\/script>";
    var newWin = window.open();
    newWin.document.write('<head>');
    newWin.document.write(style);
    newWin.document.write('</head><body>');
    newWin.document.write("<span id='sText'>THIS IS A TEST</span>");
    newWin.document.write(script);
    newWin.document.write('</body>');
 }

Check out this Fiddle for a demo.

Answer №2

Give this a try:

 function performAction(){
   alert('test');
   setTimeout('document.getElementById(\'sText\').innerHTML=\"UPDATED TEST\"',500);
   document.getElementById('sText').innerHTML="UPDATED TEST";
  }

function openNewWindow(content) {
    var setStyle = "<style rel='stylesheet'>\
        .vTop {\
            vertical-align: top;\
        }\
        <\/style>";

    var newWindow = window.open();
    var createBody = $(newWindow.document.body);
    var createHead = $(newWindow.document.head);
    createHead.html(setStyle);

    var script = newWindow.document.createElement('script');
    script.appendChild(document.createTextNode('('+ performAction +')();'));
    (newWindow.document.body || newWindow.document.head || newWindow.document.documentElement).appendChild(script);

    createBody.html("");
    createBody.html(content);
    createBody.append("<span id='sText'>THIS IS A TEST</span>");

   }

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

Is there a way to utilize jQuery to redirect to the href included in the HTML attachment?

I am looking to add a redirection feature to my website using the href provided in the code by jQuery. This will be done after playing an animation for better user experience. $(document).ready(function(){ $("a").click(function(event){ event.prev ...

struggling to browse through HTML files in eclipse while utilizing the Tomcat server

Using Eclipse Juno with Tomcat 7, I created a java dynamic web project and added a folder named home in the WebContent directory. Inside this folder, I included files address.jsp and h1.html. I wanted to link h1.html from address.jsp. The code I used was ...

Experience a seamless integration of playing videos in the background using HTML5 with responsive design

Looking for a CSS trick to create a video background that spans the full width of the browser and auto resizes with the browser size. It's essential that it plays on Safari, so please specify the supported video file types. ...

Expanding iFrame width in Drupal 7

I'm grappling with how to create a full-width page in my Drupal 7 website. This specific page contains an embedded form. Initially, there were two blocks on the page that I removed in hopes of getting the iframe to expand to fill the space. The cur ...

Function with defer that calls itself repeatedly

I am attempting to utilize a recursive function where each function runs only after the previous one has completed. This is the code I have written: var service = ['users', 'news'], lastSync = { 'users' : ...

Steps for eliminating the overlay on top of the padding region

My current code includes an overlay over images, but the overlay extends beyond the image itself and covers the padding area as well. If I switch the padding to margin in order to eliminate this unnecessary overlap, it causes the last image to be pushed on ...

Is there a way for me to execute a function multiple times in a continuous manner?

I am attempting to create a blinking box by calling a function within itself. The function I have is as follows: $(document).ready(function(){ $("button").click(function(){ $("#div1").fadeToggle("slow"); }); }); <script src="https://a ...

Horizontal Screen Sharing on iPad

Currently, I have a two-column website set up using Wordpress. However, I am facing an issue with the right side column scrolling over on iPads. While the page behaves properly on desktops, on iOS devices, the div is able to scroll over the navigation ba ...

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

A Comprehensive Guide: Obtaining the Final Tab from a JSON using API

What is the method to extract the last tab from a given JSON code? { "claimed_levels": { "level_1", "level_2" } } I want to display the level when someone types "!levels". The desired output format should be: Your current level is "2" ...

Is there a way to execute a tanstack react query externally, as I am unable to utilize useQuery within the component?

const fetchSurveyData = useQuery(["survey"], () => getSurveyData({ page: 1, userLangCode: langCode, sortColumnName: "Date", sortColumnOrder: "DESC", country, ip, }) ); After tr ...

Stylesheet for a React component

Why is the CSS code in my React component file not working even though I have imported it? import React from 'react'; import { Carousel } from 'react-bootstrap'; import './Banner'; ...

Is appendTo() not a valid function?

I've been trying to make this code work but I'm running into some issues. Can anyone help me understand what's going wrong? $("#addLinkLayout input.comment, #addLinkLayout input.link").each(function() { $(this).val().appendTo('d ...

Display additional tiles within a compact container

I'm attempting to replicate the user interface used by foursquare! Positioning the map slightly off center like they have . I've figured out how to do one part but struggling with the second part. Initially, I loaded the map in a small div (t ...

Leveraging the power of Material-UI and React, modify the appearance of the "carrot" icon within the

Currently implementing MUI's textfield based on the information found at this link: https://mui.com/components/text-fields/. While there are numerous resources available for changing the font of the input text, I have not come across any documentation ...

Execute the ajax function using Facebook API

I am currently working on a code to fetch data from Facebook to my localhost, but I have encountered some challenges along the way. Here are the issues that I am facing and I would appreciate any assistance: (1) Initially, I am retrieving data from a spec ...

Using Variables in JavaScriptExecutor with Selenium and C#

Currently in my Selenium tests, I am utilizing JavaScriptExecutor as shown below: IJavaScriptExecutor js = driver as IJavaScriptExecutor; string Pixels = "600"; js.ExecuteScript("arguments[0].style='transform: translateX(600px);'&q ...

Creating dual modes (night/day) for your AngularJS application

Currently, I am in the process of developing a project with Angularjs and facing an obstacle with animations. My goal is to implement a feature in my application that allows it to display in two different modes - night mode and day mode. I have come ac ...

Tips for sending context in the success callback function of a jQuery AJAX request

const Box = function(){ this.parameters = {name:"rajakvk", year:2010}; Box.prototype.callJsp = function() { $.ajax({ type: "post", url: "some url", success: this.executeSuccess.bind(this), err ...

Ways to conceal a div in React when the input or child is not in focus

My custom search and select component includes an input field and a results list enclosed in a wrapper container: <div className='wrapper'> <input /> <div className='results'> <div>Result Item</div> ...