What is the process for validating the CSS background-image URL using Javascript?

The concept here is to verify the URL of the CSS element's id (.boot). If the URL matches, which it does, then it should display "hello world." However, despite everything seeming correct, the expected behavior is not occurring, and the reason behind this remains unclear.

Scenario: A button is present. Upon clicking it, the CSS background URL is checked. If there is a match, an alert is supposed to be triggered.

CSS:

.boot {
    width: 1000px;
    height: 1000px;
    background-image:url(Videos/printgifstart.GIF);
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: center;
    position: fixed;
    bottom: -150px;
    right: 105px;
    z-index: 100;
}

HTML + Javascript

<div class="Logo2" id="blogo">
<h1></h1>
<div class="MirroredSmiles"></div>
<button id="ticketb" class="ticketb"
    style="height:100px;
        width: 75px;
        position: fixed;
        top: 335px;
        left: 200px;
        opacity: 0%;"
        onclick="tixbPLS">
</button>

    <script>
        var tix = document.getElementsByClassName('ticket');
        var tixb = document.getElementById('ticketb');
        var tixc = document.getElementById('ticketc');
        var sart = document.getElementById('shopdrawing');
        var sart2 = document.getElementById('shopdrawing2');
        var sart3 = document.getElementById('shopdrawing3');
        var sbakdo = document.getElementById('backdoor2');

        tixb.addEventListener('click', tixbPLS);

        function tixbPLS() {
            if (document.getElementById('boot').style.backgroundImage = url('Videos/printgifstart.GIF'))
            {
                alert("hello! world!");
            }
        }
    </script>
</div>

I've researched online and many suggest a syntax error might be the culprit. Despite trying various syntax adjustments for hours, the message "hello world" still doesn't appear as intended.

I thought perhaps it only works with images, but even after adding an image, the issue persists.

Attempts using "=" or "==" in place of each other have been unsuccessful.

Considering that everything else in the code seems fine, I experimented with replacing the original if statement with a math equation type if statement and voila, the alert functioned flawlessly.

Evidently, all components except that particular if line seem to be functioning correctly.

Answer №1

If you want to access the style sheet rules, you can utilize the CSSStyleSheet API. The MDN article provides a comprehensive explanation, as shown in this example:

document.styleSheets[0].cssRules[0].style.backgroundImage
.

Utilizing your browser's console dev tools is highly beneficial for understanding these concepts. When you query document.styleSheets in the console, it displays the style sheet object, allowing you to analyze its structure and tailor your code accordingly.

For instance, adding

console.log(document.styleSheets)
in your JS code will show an object in the console Dev tools like below:

  "0": {
    /**id:2**/
    "ownerRule": null,
    "cssRules": {
      /**id:3**/
      "0": {
        /**id:4**/
        "selectorText": ".boot",
        "style": {
          "0": "width",
          "1": "height",
          "2": "background-image",
          "3": "background-repeat-x",
          "4": "background-repeat-y",
          "5": "background-size",
    ...

In this object, the initial iteration 0 contains a nested cssRules object, with the first iteration containing a style object where the style, such as background-image, can be found. Therefore, you can fetch this data from the style sheet using:

document.styleSheets[0].cssRules[0].style.backgroundImage

It's important to note that = is used for assignment, while == and === are for comparison, with the latter being a strict comparative operator. Refer to this answer for more insights.

Another crucial point to consider is that

document.getElementById('boot').style.backgroundImage
seeks the inline style. If your .boot elements have an inline style like:

<div class="boot" style="background-image:url(Videos/printgifstart.GIF);">

the example would work with the correct comparator operand. However, if the boot elements' class is derived from a style sheet, then the CSSStyleSheets API must be utilized to read this information from the style sheet.

Note on I.E. error when using cssRules: To address the 'cssRules' issue in IE, one can include crossorigin="anonymous" in their link tag to avoid errors related to CORS headers and credentials exchange.

var tix = document.getElementsByClassName('ticket');
var tixb = document.getElementById('ticketb');
var tixc = document.getElementById('ticketc');
var sart = document.getElementById('shopdrawing');
var sart2 = document.getElementById('shopdrawing2');
var sart3 = document.getElementById('shopdrawing3');
var sbakdo = document.getElementById('backdoor2');

function tixbPLS() {
  if (document.styleSheets[0].cssRules[0].style.backgroundImage == 'url("Videos/printgifstart.GIF")') {
    alert("hello! world!");
  }
}
.boot {
  width: 1000px;
  height: 1000px;
  background-image: url(Videos/printgifstart.GIF);
  background-repeat: no-repeat;
  background-size: 100%;
  background-position: center;
  position: fixed;
  bottom: -150px;
  right: 105px;
  z-index: 100;
}
<div class="Logo2" id="blogo">
  <h1></h1>
  <div class="MirroredSmiles"></div>
  <button id="ticketb" class="ticketb" onclick="tixbPLS()">Click me</button>
</div>

Answer №2

If you want to retrieve the actual CSS property values applied to an element, regardless of their source stylesheet, you can utilize the getComputedStyle method.

It's important to note that relative URLs are resolved to their absolute versions. You can use string methods such as String#match or String#includes to search for specific values. Additionally, RegExp#test can also be employed for this purpose.

let backgroundImg = getComputedStyle(document.querySelector('.boot')).backgroundImage;
console.log(backgroundImg);
let match = backgroundImg.match(/^url\("(.+)"\)$/);
if (match) {
  // various ways to confirm the URL
  console.log(match[1]);
  console.log(new URL('Videos/printgifstart.GIF', document.baseURI).href === match[1]);
  let { pathname } = new URL(match[1]);
  console.log(pathname);
  console.log(pathname === '/Videos/printgifstart.GIF');
}
.boot {
    width: 1000px;
    height: 1000px;
    background-image:url(Videos/printgifstart.GIF);
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: center;
    position: fixed;
    bottom: -150px;
    right: 105px;
    z-index: 100;
}
<div class="boot"></div>

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

Using Cypress fixtures with TypeScript

After transitioning from using Cypress with Javascript specs to Typescript, I encountered a challenge in working with Fixtures. In Javascript, the approach below worked; however, I faced difficulties when switching to Typescript. Fixture JSON file: I sto ...

Utilizing multiple components onEnter with React-router for authentication scenarios

I am currently working on an app that consists of 2 components for a single path. The routes are as follows: <Router history={hashHistory}> <Route path="/" component={AppContainer} onEnter={requireEnter}> <Route path="/homepage" ...

Continuous horizontal columns

Is there a way to create horizontal columns with inline-blocks, like the method described here, without having vertical gaps between items on the second line due to different heights? I want to eliminate the vertical gaps between the tiles using only CSS. ...

Vuetify Card Overflow: Handling Multiline Text with Ellipsis

I have been experimenting with Vuetify cards and encountered an issue with their height. In the image below, you can see that the cards' height varies until it reaches a specified max-height of 225px. I want to implement a text-overflow: ellipsis feat ...

What is the method for producing an li and anchor tag using a list object?

Here is the response I received from my web service, and now I need to transform it into a list item tag: {"d":[{"name":"ttt","url":"bbbb"},{"name":"uuu","url":"ppp"}]} How can I create li tags based on the above output? This is the desired format for t ...

Header, footer, and sidebars are all locked in place, while the central content area is designed for

Using this Demo Template as a starting point, I am looking to create a new layout: However, I am encountering the following challenges: The two sidebars are not properly contained within the scrollable content div. The content div does not have a fixed ...

The UTF-8 encoded string in Node.js displays a mysterious black question mark

I am facing an issue with a CSV file that I receive from my supplier. They have encoded a string using UTF-8, resulting in black question marks appearing. Despite several attempts, I am unable to convert it back successfully. var common = req ...

Tips for targeting a specific div element within a webview using code in Android app development

During my exploration of focusing on a webview in Android development, I encountered a question regarding setting focus on a div element. Despite making the div element editable, neither webView.requestFocus() nor document.getElementById('container&ap ...

Display in Google Chrome without any dialogues

Hello friends, I am currently working on adding a print button to my website. I am testing it in Chrome and would like the page to be printed directly without showing any dialog boxes. However, I am facing some difficulties with this process. If anyone has ...

Should we bundle everything into one script with webpack, considering Npm and Dev dependency or just dependencies?

Imagine a scenario where we use webpack to bundle all our code into a single JS file, which automatically imports dependencies. In this case, is it necessary to include any dependencies in the package.json, or can they all be listed as --save-dev? Let&apo ...

Struggling with Responsiveness: Challenges with Detailed Information and Image Grid Design

Encountering challenges in achieving the desired responsiveness for a grid layout consisting of details and an image. The layout displays correctly on desktop screens, with details on the left and the image on the right. However, on mobile screens, the ima ...

How do I implement an onClick event for an antd message component?

I have a question and I'm hoping for some help. Here is the code snippet in question: const [msgTimer, setMsgTimer] = useState(5); message.error('some error msg', msgTimer); In the antd documentation, the message component has an onClic ...

Transferring Parameters to EJS Template in Node.js

Hey guys, I'm having an issue with rendering a MongoDB record in my .ejs file. Strangely, when I console.log the variable before the end of my route, I get the expected value. However, it becomes undefined in the .ejs file. Here is the code snippet: ...

Additional unnecessary event listeners (deleteComponent) were provided to the component but could not be inherited automatically

Dear community, I am facing an issue with emitting events from my child component to the parent. Strangely, all other components work perfectly fine with the same code except for this particular one. Let me provide you with the relevant code snippets: Ch ...

Ways to ensure that v-model does not become "true" or "false" in an input checkbox using Vue

I am currently working on a filter popup that includes a list of checkboxes. By default, some items should be selected and others not selected. I have connected these checkboxes to an object array using v-model. My issue is that when I deselect and select ...

How can you simulate a 'click' event on the currently active tab of a jQuery tab?

Hey there, I'm trying to automate a tab click on my website when a form is submitted and the return is valid. Here's a snippet of the HTML code: <ul id="tabUL" class="tabs js-tabs same-height"> <li class="current"> <a ...

Is there a way to have one element automatically expand when another is selected?

I'm currently utilizing the date and time picker from . However, I need some assistance with the current setup. Currently, the date and time pickers are in separate input fields. In order to select a date, I have to click on the Date input field, and ...

Conceal the div based on the criteria

I need an inline solution for this issue: <div id="xy<%=statusCount%>" style="margin-top: 50px;display:${<%= statusCount %>!=0 ? 'none' : ''};" class="XYZ"> This code is causing an error ...

Using Node.js with the express framework for requiring and posting data

main.js: var mainApp = express(); require('./new_file.js')(mainApp); new_file.js: mainApp.post('/example', function(req, res) { console.log(true); }); Error message: mainApp is not defined. Looking for a solution to access exp ...

Issue encountered when attempting to locate the file path within the getStaticProps function of an internal page in Next Js

I'm currently implementing a multi-language feature on my Next JS app. Below is the folder structure of my project. https://i.stack.imgur.com/5tD2G.png On the Home page (index page), I successfully retrieved the locales module using getStaticProps: ...