javascript send variable as a style parameter

screen_w = window.innerWidth;
screen_h = window.innerHeight;

I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles?

For example:

img
{
  width: screen_w;
  height: screen_h;
}

I have attempted

<script type="text/javascript"> 
<style>
img..
</style>
</script>

but it does not seem to work. Is this even possible, or is there another method for passing a variable?

Thanks in advance.

///Added

The link below -----v

suggests creating a node that represents your style

<script type="text/javascript">

var head = document.getElementsByTagName('head')[0],
    style = document.createElement('style'),
    rules = document.createNode('img { width: screen_w; height: screen_h; }');

style.type = 'text/css';
if(style.styleSheet)
    style.styleSheet.cssText = rules.nodeValue;
else style.appendChild(rules);
head.appendChild(style);

</script>

then in my HTML I just need to insert my image.

<img src="slide1.jpg">

but somehow it still does not pass through properly.

However, I can get the "document.getElementById" to work. Is there a way to do this without a button, like using onLoad()?

function changeSize()
{
document.getElementById("picture").height= screen_h;
document.getElementById("picture").width= screen_w;
}
</script>

</head>

<body>

<img id="picture" src="slide1.jpg" width="300" height="98" />
<br /><br />
<input type="button" onclick="changeSize()" value="Change size of image" />

Answer №1

It is not possible to pass variables to CSS.

But, you have the option to use JavaScript to directly alter the styling of images, such as dimensions.

Answer №2

If you want to change CSS using JS, check out this helpful question:

Learn how to create a <style> tag with Javascript

Answer №3

<script >
window.onload = function() {
    $.ajax({url: "api/<route-name>", success: function(result){
        console.log(result.data[16]['value']);
        document.documentElement.style.setProperty('--my-variable-name', result.data[14]['value']);
    }});
}
<style>
.gender_radio .radio-list .is-checked {
    background-color: var(--my-variable-name) !important;
}

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

How to retrieve the ID of the inserted record in Knex.js

I was trying to add a new note to the quoteNotes table. However, after inserting it and logging the response, I noticed that there was no record of the inserted note showing up. router.post('/:id/notes', (req, res) => { const {id} = req.para ...

What is the method for adjusting the width of a v-card based on its height?

I have a changing number of v-cards that are displayed based on their quantity. My goal is to maintain an aspect ratio of 16/9, but only adjust the width. To achieve this, I believe I need to make the width dependent on the height, although I am unsure ho ...

The function getattribute() on the edge is malfunctioning and returning a null value

Has anyone encountered issues with the getAttribute() function while creating an extension for Edge? I am currently facing a problem where it is not returning the attributes of the element that I am searching for. This is what my code looks like on Edge a ...

Notification for radio button selected

Looking to trigger an alert message when a radio button is not selected? Check out the code below: <form method=post name="spendform" id="spendform"> <input name="price" type="radio" class="invest-coin-check" id="pricemethod" > <button typ ...

jQuery's find method returns a null value

During my Ajax POST request, I encountered an issue where I wanted to replace the current div with the one received from a successful Ajax call: var dom; var target; $.ajax({ type: "POST", url: "http://127.0.0.1/participants", data: "actio ...

Is there a way to emulate synchronous behavior in JavaScript?

var routeSearch = new MyGlobal.findRoutes({ originPlaceId: search.placeInputIds.originPlaceId, destinationPlaceId: search.placeInputIds.destinationPlaceId, directionsService: search.directionsService, directionsDisplay: sear ...

"Enhance Your Website with Dynamic Text Effects using JavaScript

Is there a way to continuously animate text during the loading process of an AJAX request? I've tried implementing various methods, such as using a setTimeout function or an infinite loop, but nothing seems to work for repeating the animation once it& ...

Utilizing eval properly in JavaScript

One method I am using is to load a different audio file by clicking on different texts within a web page. The jQuery function I have implemented for this purpose is as follows: var audio = document.createElement('audio'); $(".text_sample ...

Display words on screen and then alter hue using HTML and CSS

Is there a way to dynamically change the color of text inside <a> tags from black to red after a specific time interval and keep it permanently red? do { document.getElementById("code").innerHTML +="<a>Hello World</a><br>"; awa ...

I am looking to dynamically add and remove an active link on my sidebar using JavaScript

Looking to create a dynamic website with interactive features like adding and removing active links upon clicking, and smooth transitioning between sections using JavaScript. Feel free to skip over the SVG code. HTML source code <div class="s ...

Solving repeated function firing with ng-checked in an AngularJS ng-repeat loop

In the HTML code below, there is an ng-repeat that creates checkboxes: <span ng-repeat="name in $ctrl.widgetSelectorNames" class="widget-selectors"> <label class="checkbox" for="{{name}}"> <input type="checkbox" value="{ ...

Encountered an error while trying to set up the route due to Router.use() needing

Within my app.js file, I have the following code: app.use('/', require('./routes')); //old routes app.use('/api', require('./api')); Additionally, I have an api folder containing an index.js file. This is what the ...

Redirect the Submit button to the specified URL from the form element

Looking for a way to create a form with two fields: Username and Password. Upon clicking submit, the username and password should be added to the URL in a specific format. For instance: The URL structure will remain the same, only the "username_entered_i ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

What is the best way to save Vue state in a cookie while transitioning between form steps in a Laravel application

Imagine a scenario where a user is filling out a multi-step form, and we want to ensure that their progress is saved in case they lose connection. This way, the user's data will not be lost between different form steps. In addition to saving each ste ...

Encountering undefined JavaScript functions when called from HTML

I had most of these functions working perfectly, but after restarting my program, I'm now encountering issues with undefined functions in Chrome. I can't pinpoint the exact problem, and even though I've checked through Eclipse, I still can&a ...

Using JQuery to switch out images that do not have an ID or class assigned

Currently, I am using a Google Chrome Extension to apply an external theme to a website. Unfortunately, the logo on the site does not have an ID or class that can be used to call it. I am searching for a solution to replace it with a different image. My ...

Ways to adjust timestamps (DayJs) by increments of 1 minute, 5 minutes, 15 minutes, 30 minutes, and more

Currently, I am exploring time functionality within React Native by utilizing DayJs. I have noticed a slight inconsistency when comparing 2 different points in time to calculate the time difference. Typically, everything works smoothly such as with 10:00 ...

Jquery's mouseclick event selects an excessive number of elements

Is there a way to retrieve the ID of an element when it is clicked, only if it has one? I currently have this code set up to alert me with the element's ID: $("[id]").click(function(event) { event.preventDefault(); var id_name = $(this).attr ...

Jquery Click function malfunctioning on testing environment

I'm facing a bit of challenge and could really use some assistance. I have this code snippet that functions perfectly in my test document, but once it's uploaded to the live server, everything loads correctly except for the fadeOut click function ...