Execute a function when the media attribute of a CSS link is modified

Looking to dynamically adjust the media attribute of a CSS link tag and execute a function after the new styles are applied.

Here's how my CSS stylesheet link tag looks:

<link href="print.css" rel="stylesheet" media="print">

In my JavaScript code, I aim to switch the media attribute from print to all, and then trigger a function once the updated styles take effect on my page.

The current approach involves checking and updating as follows:

if (myCSSlink.getAttribute("media") === "print") {
                myCSSlink.setAttribute("media", "all");
                myCSSlink.onload = () => {
                    //perform necessary tasks
                };

}

I'm assuming that when the media attribute is modified, the CSS will reload. However, my code within the arrow function doesn't seem to be functioning correctly. What could be a better way to handle this situation?

Answer №1

To accomplish both tasks of changing the media attribute and executing a custom onload function, you can assign an onload handler to handle both actions.

function setMediaAndExecuteFunction(link) {
    link.setAttribute('media', 'all');
    yourCustomFunction();
}
<link href="style.css" rel="stylesheet" media="screen" onload="setMediaAndExecuteFunction(this);">

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

What is the best way to incorporate bootstrap into a react project?

import './App.css'; import TodoList from './components/TodoList'; import 'bootstrap/dist/css/bootstrap.min.css' function App(){ return( <div className="my-todo-app"> <TodoList/> ...

Posting and deleting data in AngularJS using HTTP requests

Incorporating both angularjs and c# webapi in this situation. My approach involves calling the webapi from angularjs and passing a json array. Here is the Angularjs code snippet: factory.delete = function (json) { var url = 'myUrl'; ...

Bootstrap CSS allows for easy closing of modals

Having trouble with the Twitter Bootstrap CSS causing my animation to open with a fade and immediately close. Not sure why this is happening, can anyone provide assistance? Update: Turns out, the bootstrap.css file already has Modals implemented. Using bo ...

Cannot get Firebase's set() method to work when called within onAuthStateChanged() function

As I embark on developing my first significant web application using ReactJS with Firebase as the backend database, everything was progressing smoothly until a troublesome issue surfaced. The hurdle I encountered involves saving user information upon thei ...

Is there a way to customize the appearance of a clicked link using only CSS?

Is it possible to style a clicked link using only CSS in order to provide user feedback that the link has been clicked and is taking the desired action? While I could use JavaScript to listen for click events and apply a desired class for feedback, a CSS- ...

Javascript and the output of Ajax request

I'm facing an issue with my JavaScript files interacting with the response from an ajax request. It seems that the JavaScript is unable to read the response from the ajax call. My question is, how can I get my jQuery plugin to access the classes in t ...

When using jQuery to enable contenthover on divs, they will now start a new line instead of

I've been working on achieving a layout similar to this, with the contenthover script in action: Mockup Draft Of Desired Look However, the result I'm getting is different from what I expected, it can be seen here. The images are not aligning co ...

Steps for eliminating QRcode warning in npmjs package

Issue: Warning Message (node:24688) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) Seeking Solution: How can I prevent this warning ...

How to utilize jQuery's each function to parse JSON from an array composed of multiple arrays

Note: This information has been heavily updated, although progress is slow but steady. I am working with an array of JSON arrays that I need to parse from a remote source. However, for illustrative purposes, I have included a structural example in my Java ...

It seems like the method has already been executed despite encountering an unexpected end of JSON input error

Currently, I am utilizing the etherscan API to retrieve logs for certain events. Although my JSON parsing method seems quite traditional, an error is being thrown stating "unexpected end of JSON". function getEventHistory() { const topic0 = web3.util ...

The function XmlHttpRequest getResponseHeaders() is not providing a complete list of all headers

Has anyone encountered the issue where jQuery's xhr method, getAllResponseHeaders, only displays the "Content-Type" header when trying to retrieve response headers from an ajax request? Below are the response headers: Access-Control-Allow-Credentia ...

Having trouble with individuals gaining access to my gh-pages on Github

After creating a gh-pages repository on Github to showcase my portfolio, I encountered an issue where visitors were being prompted to log into Github in order to view the page. Gh-pages are intended to be public, so I am unsure why this is occurring. My ...

Steps for adding a time display box to a time progress bar

There is a time progress bar with code provided. How can I make sure the yellow bar moves according to the time and display the time in a box? https://i.sstatic.net/ZgPOe.png var timer = 0, perc = 0, timeTotal = 2500, timeCount = 1, cFlag ...

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

The functionality of smooth scrolling is not compatible with the overflow-y property

Looking to implement a smooth scroll feature, I came across an example online and tried to adapt it. Here's the code I'm working with: https://jsfiddle.net/4DcNH/144/ I've added specific conditions to the html and body elements (changing t ...

Is the image flickering non-stop when the button is pressed?

Every time I push the button, the image on the HTML 5 canvas flickers. After investigating, it seems like the issue might be related to the ctx.clearRect(0,0,100,500) function. Any suggestions on how to fix this problem? I'm currently working on anim ...

Slider with a progress bar

Have you ever wondered if it's possible to create a progress bar using an input range? Imagine someone entering a number and the bar moves to the right, changing its background color on the left side of the thumb based on the size of the number. Check ...

What is the best way to retrieve and save the titles of checked boxes in the Autocomplete using state with hooks?

I've implemented the React Material-UI Autocomplete feature with checkboxes in my project. Here is what I have so far in my code (check out demo.js for details): https://codesandbox.io/s/material-demo-rxbhz?fontsize=14&hidenavigation=1&theme=d ...

The $in operator for Mongoose isn't functioning properly on Node.js

How can I create a query that matches a specific value within an array in MongoDB using the $in operator? I want to match only one value from the array, not all of them. This is how I have coded it so far: const getSearch = async (req,res) => { try ...

Limit the y-axis on CanvasJS visualization

Is it possible to adjust the minimum and maximum values on the y-axis of the graph below: new CanvasJS.Chart(this.chartDivId, { zoomEnabled: true, //Interactive viewing: false for better performance animatio ...