Enhance your JQuery skills by implementing variables within the .css() function

Attempting to randomly assign values to an image's left and right properties using JQuery. Here is the code snippet:

var sides = ["left", "right"]
var currentSide = sides[Math.floor(Math.random() * sides.length)];
$("#"+currentImage).css({currentSide : "80px"});

An array called 'sides' holds either 'left' or 'right', with one being randomly selected to set the CSS property of the element to either right: "80px"; or left: 80px;

However, this implementation is not functioning as expected. Manually setting it e.g.

$("#"+currentImage).css({"left" : "80px"});
works fine, indicating that passing variables to the .css() function may be causing the issue.

Any suggestions on how to resolve this?

Answer №1

If you intend to generate an object with a dynamic key, then bracket notation is required. In this scenario, the object being created has a key of currentSide and not left/right.

To achieve this, you can utilize:

$("#"+currentImage).css(currentSide, "80px");

Answer №2

To prevent encountering similar issues with various applications that lack an alternative syntax like $().css(), I will provide a more general answer. This method allows you to apply multiple styles using just one .css() function call.

let directions = ["up", "down"]
let currentDirection = directions[Math.floor(Math.random() * directions.length)];
let styles = {};
styles[currentDirection] = "50px";
$("#"+currentImageID).css(styles);

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 preventing me from accessing my session array in this.state.props from my mapStateToProps in React-Native Redux?

I am currently facing an issue with my Redux store setup. I am attempting to store an array of Session objects, where each Session object contains an array of Hand objects. However, when trying to access my store using `mapStateToProps`, none of the option ...

What is the best way to insert fresh input values into a different element?

click here to view image description I am working with an input element where I take input values and store them in an element. However, I would like to know how to input new values into the next element. Any assistance would be greatly appreciated. Thank ...

.encounter issue with loading Internet Explorer

Currently, I am utilizing the .load method to load some data into a div. It is functioning properly overall, but when attempting to specify and load a particular ID from the HTML, Internet Explorer fails to load anything. For example: $('div.myDiv&a ...

Animating components when they first mount in React

I'm attempting to implement an onMount animation in React (and Tailwind if relevant). The code I currently have is as follows: const Component = () => { const [mounted, setMounted] = useState(false) useEffect(() => { setTimeout(( ...

Place a user input field within a div element having the specified class

I am trying to insert an HTML input element into the following div: <div class="sss" style="padding-top:2px"> <center> <input value="test1" name="name1" type="submit" > <input value="test2" name="name2" type="submit"> </c ...

Excessive Font Awesome Icons causing navigation bar to appear oversized

My Font Awesome icons are causing my navbar to expand in height. Despite resetting all margin and padding to 0, adjusting the margins and paddings of the icons has not helped. I even tried setting negative top and bottom margins/paddings. https://i.sstati ...

What is the best way to retrieve router parameters within a JSX component?

How can I pass the post ID as a prop to the EditPost component in order to edit it? render() { return ( <Router> <Switch > <Route path="/edit/:id"> <EditPost index={/*what do I do here?*/} /> ...

Using jQuery to create a dynamic fullscreen background image that responds to mouse movement

I am currently working on creating a dynamic full screen background that responds to the movement of the mouse. The idea is that as you move the mouse around, the background image will shift accordingly. For instance, if you were to move the mouse to the ...

Ways to access a field value in SAPUI5

As I delve into OPENUI5/SAPUI5, I'm faced with the task of accessing data for the controls I've implemented. For instance: <Label text="Amount" /> <Input id="inputAmount" value="{Amount}" /> <Text id="lblCurrency" text="USD" > ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

Encountering a browser error when trying to access a C# method via AJAX: Javascript

I'm having trouble connecting to my Webservice. I keep getting an error 404, even though everything seems like it should be working fine. The issue started when I moved the code from my *.cshtml file into a separate .js file. The Javascript file is l ...

What is the top JavaScript library for compressing and adding files for transfer to an API?

In the process of developing a Vue.js application, I am facing the task of zipping data into files, adding them to a zip folder, and then sending the zip folder to an API. After researching, I found two options - Zip and JSZip, but I'm uncertain about ...

contrasts in regex special characters: .net versus javascript

Here is my current javascript implementation: EscapeForRegex = function(input) { var specials = ["[", "\\", "^", "$", ".", "|", "?", "*", "+", "(", ")", "{", "}"] for (var k in specials) { var special = specials[k]; ...

Manipulate form fields via jQuery in Django to dynamically hide or show them based on certain

I am currently working on creating a universal method to manage the display and hiding of specific fields based on checkboxes. In many of my projects, I encounter forms that include checkboxes where certain fields are associated and will appear or disappea ...

Troubleshooting: AngularJS filter is not functioning properly in combination with jQuery

I have a collection of items stored in the variable $scope. I have connected these items to jQuery events and added an input field for filtering. Everything is functioning properly. However, when I enter text into the input field, the filtered out items r ...

Is it possible to integrate a Backbone app as a component within a separate app?

I am currently in the process of familiarizing myself with Backbone.js and front-end development, as my background is more focused on back-end development. I have a question related to composition. Imagine that I need to create a reusable component, like ...

Is the Owl carousel Auto Play feature malfunctioning when hovered over?

I seem to be encountering an issue with the auto play functionality of the owl carousel. I have uploaded and included all the necessary files, and it is functioning properly when initially loaded. The auto play feature works perfectly, but when I hover ove ...

Ajax - Retrieving data from a different webpage

My index.php contains the following HTML: <div id="showDetails"> </div> <div id="showList"> </div> And this Ajax function is also in index.php: function ...

What is causing the initial activation of the <button> within a form?

Within my <form>, I have included 2 submit buttons. The first button looks like this: <button class="regular" id="geocodesubmit" style="height:40px;">Set Location</button> The second button looks like this: <button type="submit" ...

Setting the z-index for a JavaScript plugin

I need help with embedding the LinkedIn plugin into a website that has stacked images using z-index for layout. I have tried assigning the plugin to a CSS class with a z-index and position properties, but it hasn't worked as expected. Can anyone sugge ...