Enhance your webpage with custom styling using the html() method in jQuery

Adding style to my website using the .html() method is something I'm looking to do.

I've attempted this:

Using jQuery:

if ($('#checkbox:checked') > 0) {
    $("body").html("
        <style>
            .selected{
                background-image: url('http://www.website.com');
            }
        </style>
    ");
}

However, it's resulting in an error message:

SyntaxError: unterminated string literal

Answer №1

If you want to utilize multiline strings in JavaScript, remember to add backslashes at the end of each line. Here's an example:

var sample = "This\
           is\
           a\
           multiline\
           string.";

Additionally, when inserting HTML content into the body without replacing it, follow this format:

if ($('#checkbox:checked').length > 0) {
    $("body").append("\
        <style>\
            .selected{\
                background-image: url('http://www.newwebsite.com');\
            }\
        </style>\
   ");
}

(I have included .length in your selector to ensure proper comparison with an array)

I haven't tested it, but in theory, it should work.

Answer №2

Give this a shot:

if( $('#checkbox:checked').length > 0 ) {
    $("body").append("\
        <style>\
            .highlighted{\
                background-image: url('http://www.example.com');\
            }\
        </style>\
    ");
}

Answer №3

For optimal functionality, it is recommended to condense your script into a single line:

if ($('#checkbox:checked') > 0) {
    $("body").html("<style>.selected{ background-image: url('http://www.website.com');     } </style> ");
}

Alternatively, you can append slashes to the end of each line for clarity.

Answer №4

KEEP IT SIMPLE

$('#checkbox').on('change', function () {
    (this.checked) ? bgImage='url("../images/picture.jpg")' : bgImage='default';
    $(".selected").css('background-image', bgImage);
});

Ensure that your default value is defined within the .selected class.

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

In what way does the map assign the new value in this scenario?

I have an array named this.list and the goal is to iterate over its items and assign new values to them: this.list = this.list.map(item => { if (item.id === target.id) { item.dataX = parseFloat(target.getAttribute('data-x')) item.da ...

"The Perfect Match: Combining ASP.NET AJAX TOOLKIT with JQUERY UI DIALOG for Optimal Timing

My current project involves the use of the AJAX Toolkit, which is a departure from my usual work with jQuery AJAX. While both have their challenges, I am facing a timing issue that I need help resolving. The task at hand is to display an edit form in an o ...

CSS cascading not happening

Within the usersettings.css.erb file, line numbers are provided for easier reference. 11 #userSettingMain .form-horizontal .controls { 12 13 margin-left: 30px; 14 } 15 16 #user_birthday_3i{ 17 18 margin-left: 0px; 19 } U ...

Styling PHP echo in HTML

This seems like it should be simple, but there's clearly something I'm missing here. If anyone can point me in the right direction and give me a hint, I would truly appreciate it! Thank you and have an amazing day! <?php $code = '1 ...

JQuery Function for Repeatedly Looping through Div Elements

I've been experimenting with creating a loop that alternates the fade-in and fade-out effects for different elements. This is what I have so far: setInterval(function() { jQuery(".loop").each(function(index, k) { jQuery(this).delay(1200 ...

Differences in behavior of constructors when utilizing ES6 shorthand notation

ES6 introduced a new way to initialize objects with functions and properties using shorthand notation. // ES6 shorthand notation const obj1 = { a(b) { console.log("ES6: obj1"); } }; // ES5 var obj2 = { a: function a(b) { con ...

Creating consistent image sizes in Bootstrap

I'm currently using Bootstrap 4 to showcase multiple images on my website. I have attempted to apply the Grid system as per Bootstrap's guidelines, but the display of the images is not aesthetically pleasing due to their uneven sizes, which can b ...

The ins and outs of import and export output explained

I'm currently struggling to understand the output of Import/Export Statement. For example, if I were to write this code: import React, { Component } from 'react'; import Cperson from '../components/person/person.js'; console.log ...

Having trouble getting dropdown values to work properly in HTML?

Currently, I'm encountering an issue with a drop-down menu that contains the days of the month (ranging from 1 to 31). When I input "22," it seems to default to loading option "20" instead. Displayed below is the code snippet that I am currently usin ...

Can you explain the role of the faceVertexUV array within the three.js Geometry class?

Currently, I am utilizing three.js to create curved shapes using parametric functions. Within the THREE.js javascript file, there is a function called THREE.ParametricGeometry that continuously adds 2D vectors to the faceVertexUvs array. I am curious abo ...

Issue with Ionic ng-click not triggering

I am currently experimenting with an Ionic application that utilizes a Firebase backend. The issue I'm facing is that the ng-click="loginUser(user)" function does not seem to be triggering. When checking the console, it only displays Signed Out from ...

Issue encountered while attempting to transfer data via the $.ajax method

I created a poll form using radio buttons. To submit the form, I utilized $.ajax. However, when I tried using $("#polling").serialize() to gather the data, nothing was sent or requested... Could the issue be related to the radio buttons? $(function( ...

CSS: Achieving Layered Effect with Child Image Over Parent Background Image

I have set a background image on the .section class in my CSS stylesheet. The background also has an opacity effect applied to it. However, I am facing an issue where the child img (which is a transparent png) is displaying behind the background image of t ...

The designated function name can be either "onButtonClick" or "onClickButton"

I am a Japanese developer working on web projects. Improving my English language skills is one of my goals. What would be the correct name for a function that indicates "when a button has been clicked"? Is it "onButtonClick"? Maybe "onClickButton"? Co ...

Creating a unique custom error message for every validation option

I am using a Joi schema and I would like to set custom error messages for each validation option. Here is an example of my schema: const schema = Joi.object().keys({ name: Joi.string() .min(5).error(() => 'first message') .ma ...

Using jquery ujs to stop a form submission if the field is empty

I'm facing an issue with a form that submits using data-remote => true. The form consists of a single field, a textarea. My goal is to block the submission of the form if the textarea's length is 0 and only permit form submission if the lengt ...

Implement a mandatory route in Express

Is it possible to enforce a specific route? Scenario: Consider the following route A: notiSchema = notification model router.get('/set', function(req, res){ User.findById("userId", function(err, foundUser){ foundUser.notiSchemaSen ...

The issue with my Wordpress frontend ajax form not functioning as expected

I've been struggling with this issue for hours now. I'm still new to Ajax, so I might be overlooking something simple. Please help me out before I pull all my hair out! In my functions.php file // Setting up the Ajax Quote Box function ajax_quo ...

How can I make vuetify carousel arrows unique to my design?

Hey there, I'm currently working with this template in my application: <v-carousel cycle height="300" class="carousel" hide-delimiters> <template v-slot:prev="{ on, attrs }"> < ...

Implementing the sticky class once the user scrolls past a certain element

I am facing an issue in my vue component where I need to add a fixed class to an element when the user scrolls past it. However, the sticky console.log seems to be firing on every scroll instead of only when the element is passed. I also want to remove the ...