Generating a CSS rule based on a query string

Receive query string

var queryString = window.location.search;

Eliminate ? from the start of the query string

queryString = queryString.substring(1);

Query string handler

var parseQueryString = function( queryString ) {
    var params = {}, queries, temp, i, l;
    // Break down into key/value pairs
    queries = queryString.split("&");
    // Convert the array of strings into an object
    for ( i = 0, l = queries.length; i < l; i++ ) {
        temp = queries[i].split('=');
        params[temp[0]] = temp[1];
    }
    return params;
};

// Query string object

var pageParams = parseQueryString(queryString);

// CSS variables

var target = pageParams.target;
var prop = pageParams.prop;
var value = pageParams.value;

// Unable to get it working -->

jQuery(target).css({
    prop : value,
});

I aim to input a query similar to this "?target=body&prop=display&value=none" and hide the whole body or target specific elements by their class.

Answer №1

Using prop as a key-variable for the object passed to .css() is not feasible. It would result in the literal string 'prop'. Instead, consider using:

jQuery(target).css(prop,value);

Caution: Watch out for that trailing comma in the hash (after value). Some browsers may throw an error at that point.

Answer №2

To easily create a CSS object that can be passed to jQuery, I would suggest the following approach:

// Define and populate css object
var cssObject = {};
cssObject[property] = value;

After implementing this code snippet, everything seemed to work perfectly for me. For more details, you can check out the complete solution here:

http://jsfiddle.net/abc123/7/

I also recommend using a regex to remove any question marks as indicated in the comment below.

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

Solution for Organizing Tables

I've sourced data from various JSON API links and displayed it in a table. Currently, my code looks like this: <script src="js/1.js"></script> <script src="js/2.js"></script> Above this code is the table structure with <t ...

The function `jQuery .html('<img>')` is not functional in Firefox and Opera browsers

This particular code snippet jq("#description" + tourId).html('<b>Opis: </b> '+ data); has been tested and functions correctly in Internet Explorer, Firefox, and Opera. However, when it comes to this specific piece of code jq("#i ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

How to toggle the visibility of specific div elements within a v-for loop depending on their content?

I am working on a scenario where I have a collection of objects displayed in a v-for loop. Each object has a specific key value pair, and I want the user to be able to toggle a button outside the loop to show or hide elements based on that key value. Initi ...

Can I simultaneously execute nodemon and browser-sync using a single npm script for an Express application?

Within my Express application, I utilize both nodemon and browser-sync in conjunction. These npm scripts are included in my package.json: "scripts": { "start": "node ./bin/www", "start:nodemon": "nodem ...

Tips for aligning buttons vertically within the form-row class in Bootstrap 4

I'm facing an issue where I cannot get a set of buttons in line with labels when using different column widths in Bootstrap. The behavior of a button assigned to a specific column width, like col-3, is not the same as a button assigned with automatic ...

NodeJS: The functionality of my node files relies on the variables defined in another file

For my nodejs app, I have created a script called app.js that serves as the entry point. This script initializes both the expressjs app and the http server. To clarify: The modules mentioned are not npm modules; they are custom files that I have written m ...

The specified type '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' is not compatible with the expected type

I've been working on a UI layout that includes checkboxes on the left, a data table on the right, and a drop zone box. The aim is to keep the table data updated whenever a new file is dropped, and also filter the data based on checkbox selection. I ma ...

When using jQuery's $.post method and encoding data as JSON with json_encode(), the output includes quotation marks

When I make a $.post call using jQuery, the returned string is enclosed in quotes due to the json_encode line. Is there a way to prevent these quotes from being added? Could it be an issue with my $.post call? $.post("getSale.php", function(data) { ...

Float: A threshold reached when adding 1 no longer has any effect

In the realm of programming, float serves as an estimation of a numeric value. For example, 12345678901234567890 === 12345678901234567891 evaluates to true However, 1234567890 === 1234567891 yields false Where does the equation num === num+1 reach a br ...

Struggling to implement custom media queries in a bootstrap theme

I've customized the Twitter Bootstrap layout for my website, and everything is looking great except for the @media queries. Can anyone help me figure out what's going wrong? HTML: <section id="lessons" class="bg-black no-padding lesson-conte ...

JavaScript allows the "Enter" key to perform a specific action

Currently utilizing Bootstrap and jQuery for my project. Encountering an issue where pressing the enter key after filling in the tracking field does not trigger any action, as I am not using the form attribute. However, when I input something and click the ...

Step-by-step guide on sorting WordPress posts by a custom field date

I've created an event sidebar section that will only show the next 3 upcoming events. I have successfully set up the custom post type and custom fields, but I am struggling to figure out how to order the posts based on the start date of the events, wh ...

Connecting files within a directory using the Shiny framework

I am working on a shiny app that will display the files within a folder and give users the option to open or download them. For example, let's say I have 3 files in a folder: file1.txt file2.bmp file3.jpg I want my app to list these files and allo ...

Having trouble getting $.ajax to work with ASP.NET?

I've been attempting to use the $.ajax method to fetch NORTHWND Employees details based on specific search criteria. However, I'm consistently encountering issues where the country and title variables are returning as null. I'm struggling to ...

Searching for an element by a unique custom attribute in jQuery

I have implemented the CheckBoxList control in Asp.Net and customized it by adding a custom attribute for Value after populating the data. Although I can retrieve the selected checkboxes using jQuery, I am facing difficulty in identifying a specific check ...

Is there a way to incorporate a Laravel foreach loop within a JavaScript file?

I recently added a select-box using jQuery: <span onclick="createProduct()">Add New<i class="fa fa-plus"></i></span> <script> function createProduct() { var html = ''; html += ' <div clas ...

JSON.stringify not behaving as anticipated

I am working on the code below; var data = []; data['id'] = 105; data['authenticated'] = true; console.log(data); var jsonData = JSON.stringify(data); console.log(jsonData); The initial console.log is displaying; [id: 105, authenti ...

Creating a fresh array by applying a filter and assigning keys

I am facing an issue with my array structure, it looks like this, [ [ "Show/Hide", "P000", "MAX-CT05 FVM2-", "S", 1532, -9.5929406005, null, null, ...