Printing feature causing conflicts with other jQuery event listeners

After successfully printing the content of a div on click, I encounter the issue that none of my jQuery events work after canceling the print preview. This seems to happen without requiring a page refresh.

I'm puzzled as to why this occurs and would like to avoid having to refresh the page post-print preview.

Here is the JavaScript code snippet responsible for handling the print functionality:

$('.btn li:nth-child(1) > a').on("click", function(e){  
    var divElements = document.getElementById("divContentId").innerHTML;
    var oldPage = document.body.innerHTML;
    document.body.innerHTML = 
        "<html><head><title>Print Title</title></head><body><table width='670'><tr><td><h1>This is Print Preview Title</h1>" + divElements + "</td></tr></table></body>";
    setTimeout(function() {
        window.print();
        document.body.innerHTML = oldPage;
        window.close();
      return true;
    }, 250);
  $(".btn-options").hide(); // The event following the cancelation of the print preview does not trigger and other events fail to work
});

Answer №1

As mentioned earlier in the comments, a potential solution could be to use the print function within an iframe:

$('.test').on("click", function() {
  var divElements = $("#divContentId").html();

  $('<iframe class="hidden" id="printer"></iframe>').appendTo('body');
  var printer = $('#printer');
  printer.contents().find('body').append("<table width='670'><tr><td><h1>This is Print Preview Title</h1>" + divElements + "</td></tr></table>");
  printer.get(0).contentWindow.print();
  printer.remove();

  //Additional actions can be performed here ...
});

For a functional demonstration, visit this JSFiddle link. (Unfortunately not achievable in a Snippet format)

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

CSS: choose all elements starting from the n-th element and apply styles to them

Is it possible to choose specific child elements beyond the first few in a parent element? To clarify, let's say there's a div containing 7 spans. How can I select only the spans starting from the 3rd element onwards - so specifically span 4, 5, ...

Issue with loading glb file in three.js: The 'format' property is not compatible with this material

When loading a .glb file I created in Blender using three.js, I am encountering an error message three.module.js:7950 THREE.MeshStandardMaterial: 'format' is not a property of this material.. The rest of the content loads correctly. What does thi ...

An approach to transferring the ID of a multiple dropdown within the $.each function

function filterFields(classname, value, chkClass) { var checkedfields = []; $.each($("."+classname+" option:selected"), function(){ checkedfields.push($(this).val()); }); $('#'+chkClass+'Filters').val(ch ...

"Troubleshooting Issue: ASP.NET MVC - Unable to make JQuery call from URL without specifying

My current situation involves a http://localhost:54393/CreateTest/4fwp36 link that is functioning properly. However, when I attempt to call http://localhost:54393/CreateTest/RemoveControlsNew using jQuery ajax, it fails to work and throws an error. Moreove ...

Error: The API call response could not be shown on the webpage

Upon exploring the React App.js page, I discovered that I am making calls to a Django Rest API and receiving an array as a response. Within this array, there are nested components that should be listed in my code. However, when attempting to display multi ...

Browse through the options in the dropdown list -Angular 6

I am looking to implement a filtering feature in my Angular app where data can be filtered based on the selected product number from a dropdown menu. The product data is structured in JSON format as shown below. component.ts productlistArray = [{ num ...

How can we improve our vertical division method?

Looking for a more efficient way to create a vertical divider between two divs. I want the divider to be centered between the "why choose" and "gallery" sections. Here is an example of what I'm trying to achieve. I've attempted the following co ...

Can CSS interfere with the execution of the document ready function?

When I have a large CSS file on my page, will my document.ready execution wait for the CSS file to load? <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="large-amount-file.css"> </head ...

Is the margin missing from the first `li` element in the second column of the `ul`?

How can I apply a top margin to each li element within a ul element that utilizes the css property column-count: 2? I am facing an issue where the margin is being applied to every li element except the first one in the second column: ul { column-count ...

"Encountering the same problem with migrating from jQuery to PHP,

I am encountering a similar issue as before, but this time it is more specified and includes additional information. Below is the form I have been using: <form method="post" action=""> <table> <tr> <td>Login</td>< ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

Upon re-executing PHP following an Ajax request

I am working on a select menu that can submit without reloading the page. Here is how it currently functions: <select id="option" name="option"> <option value="15">15/option> <option value"30">30</option> <option value"90"> ...

Getting a consolidated outcome by selecting from a dropdown menu, pulling data from separate Angular arrays

I am currently facing an issue and I could use some guidance. My problem involves a dropdown menu where I make a selection, which then retrieves matching results from two separate Angular data arrays. In this scenario, I have two Angular scopes named $scop ...

Dynamically alter the class of the menu on the master page

Can anyone provide guidance on updating the CSS Class name of a menu located in the Master page from a Child Page? I aim to switch the class to "active" whenever any child form of the menu is open. Are there any C# or JavaScript solutions for this scenar ...

Javascript window.scroll function malfunctioning in some browsers while running in localhost

Check out this codepen link where everything is working, but unfortunately not locally: https://codepen.io/LoudDesignStudios/pen/RwxPJKY <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> < ...

What repercussions may occur if the Webcam/Camera remains active?

I am currently working on creating a web application using JavaScript and I need to allow access to the camera (whether it's the built-in camera or an external webcam). Are there any potential issues that could arise in the near future? ...

What is the best way to enclose all succeeding elements with an HTML tag after a specific element?

In my project, I am integrating Vue 2 with Sanity.io and I am looking for a solution to wrap all elements that come after a specific element with an HTML tag, and then wrap this element along with the following elements with another HTML tag. For instance ...

Tips for incorporating external JavaScript code into React components

I have been tasked with integrating a graphical widget into a React component for a project I am working on. The widget_api code provided by RIPE Stat is required to accomplish this. Previously, in HTML5, the integration was successful using the following ...

React router refreshes children when switching routes, without needing to reconcile

I am facing a scenario where multiple routes share the same component and I need to maintain its state, but the current behavior makes it nearly impossible. Check out this live example (observe the elapsed seconds): View the code on CodeSandbox: https:// ...

How can I transfer a JavaScript variable to a Django template before submitting the form?

Trying to fetch a selected approver and validate before submitting a form in Django has proven quite complex. I've made significant progress, but I'm stuck on figuring out how to "get" the translated ID in the Django template. I have the ID, but ...