Can you guide me on setting a background image URL for rails using javascript?

Within my Rails application, I have a collection of content paired with image buttons (each piece of content has an associated image). When a user clicks on one of these buttons, my goal is to display the corresponding image.

All of my images are stored under assets/images/preview/id1.png in the project. In my JavaScript code, upon clicking the view-content button, I aim to change the background image to show the relevant image based on the ID assigned to that button. How can this be achieved?

How do I set the image URL for the background image:

_page2.html.erb

<div class="content">
<table>
    <tr>
        <td> Content related to the image </td>
        <td> <div id="<%= content[:lable].delete(' ')%>" class="view"> VIEW-IMAGE </div></td>
    </tr>
    <tr>
        <td> Content related to the image </td>
        <td><div id= "<%= content[:lable].delete('')%>" class="view">VIEW-IMAGE</div></td>
    </tr>
</table>

content/preview.js

$('.view').click(function (event){
     var image = $(this).id
   $(this).css("background", "url(image.jpg) no-repeat");
    });
    });

Link to Jsfiddle: http://jsfiddle.net/bkrx2rxz/1/

In content/preview.js

$('.view').click(function (event){
    $(this).css("background", "url(sample.png) no-repeat");
    });

I attempted to use the aforementioned code. However, it seems like the image is not loading because it searches for images in content/sample.png instead of assets/images/sample.png.

Answer №1

Give this a shot

$('.view').click(function (event){
    $(this).css("background", "url(assets/images/sample.png) no-repeat");
    });

UPDATE

If you want to customize the background based on the id of the element, adjust the code as follows:

$('.view').click(function (event){
  var id = $(this).attr('id');
  $(this).css("background", "url(assets/images/" + id + ".png) no-repeat");
});

Answer №2

By simply adding a slash before the assets and removing the images, I was able to make it work.

$('.view').click(function (event){
    $(this).css("background", "url(/assets/sample.png) no-repeat");
    });

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

Is the AJAX call returning JSON data?

Currently, I am utilizing AJAX technology to scrape player names and their respective ratings from a website. The approach I have chosen involves having AJAX return a JSON object which is then manipulated using jQuery to append each element of the JSON obj ...

Tips for declaring the project npm registry within the package.json configuration file

Currently, I am juggling multiple projects simultaneously and facing the issue of each project having a different node module registry. For instance, project A sources its modules from http://registroy.foo.com, while project B pulls modules from http://re ...

Submitting information from a lone row within a table that is contained within a single form

Within my form, there is a table containing records generated by a for loop iterating through items in a list. Each record has a submit button that triggers an AJAX call to serialize and POST the form data to the controller. The goal is to only POST data f ...

Executing multiple functions in a specific order within an asynchronous grunt task using async

I am facing an issue with my grunt tasks that run asynchronously using this.async. I have some asynchronous functions in the code and for a few tasks, I need them to run in series. To achieve this, I am utilizing async.series from the async npm module. How ...

Guide to customizing action button color on MatSnackbar?

Currently, I am encountering an issue with the snackbar in my Angular 9 project. Despite adding CSS styles to both the component.scss file and the global style.scss file, the action button on the snackbar displays the same background and text color. In an ...

When one AJAX call is blocking another AJAX call

After my webpage loads, I initiate an Ajax call to a php script that updates the server. However, this script can sometimes take longer than a minute to finish, preventing me from executing other necessary Ajax calls while it's running. How can I ensu ...

"Clicking on a child link within a Bootstrap5 dropdown causes the dropdown menu

I integrated a dropdown feature to create a navigation menu. The issue I encountered is that when I expand a heading and click on a sublink, the menu collapses instead of redirecting me to the intended link. I suspect this has something to do with the co ...

Node, Express, and Angular redirection problem encountered

I have a web application built with node, express, and angular. The app consists of two main pages - a user profile page and a login page. My goal is to redirect any user who is not logged in to the login page when they try to access the profile page. Howe ...

Angular rest call is returning an undefined response object attribute

When attempting to retrieve the attribute of a response object, it is returning as "undefined". var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', function($scope, $http) { $scope.addNewChoice = functio ...

Run Javascript code if a specific CSS class is present on an element

Whenever a user enters an incorrect value into a textbox on my page, an error message is displayed within a div with the class 'validation-errors'. I'm looking for a solution to trigger a javascript function (which adds a CSS property to a ...

Using jQuery, remove any white spaces in a textbox that are copied and pasted

There is a textbox for entering order IDs, consisting of 7 digits. Often, when copying and pasting from an email, extra white spaces are unintentionally included leading to validation errors. I am looking for a jQuery script to be implemented in my Layout ...

What are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

"AngularJS offers a unique way to include alternative text in placeholders and titles using

I need to implement an input field (<input..>) with a placeholder and title for tooltip that functions in the following way: There is a variable called "myString" which can either be undefined/empty or contain a string. When empty, a default string ...

Guide on building a multi-page application using Vue or React

I find myself a bit confused when it comes to single-page applications versus multi-page applications. While I am aware of the difference between the two, I am struggling with creating a MPA specifically. Up until now, I have built various apps using Rea ...

Best method for linking asynchronous requests using axios

Is it possible to make an API call using axios based on the response of another initial API call, all within asynchronous functions? I attempted the following approach with await/promise: function fetchUserDetails(userId) { return axios.get( "https://a ...

Tips for adjusting image dimensions with url() method in css

I have successfully incorporated collapsible functionality on my page. I would like to display a down arrow image instead of the default '+' symbol on the right side of the collapsible section. To achieve this, I can use the following CSS code s ...

The member 'email' is not found in the promise type 'KindeUser | null'

I'm currently developing a chat feature that includes PDF document integration, using '@kinde-oss/kinde-auth-nextjs/server' for authentication. When trying to retrieve the 'email' property from the user object obtained through &apo ...

How to use jQuery to dynamically identify the current div on a page when scrolling, even with an unpredictable number of divs

I have a container with multiple A4 pages (number varies) and I am trying to determine the current page being viewed. Below is my code: <div class="mycont"> <div id="page1" style="width: 21cm; height:29.7cm; border: ...

Learn how to dynamically insert input data into a table based on a specific ID in React JS!

[Help needed! I am trying to store the marks, id, and name values of each cell in objects of an array. However, I am not getting the correct answer. Can someone guide me on how to properly store the marks and id of each cell in objects of an array? const [ ...

Adding space between the heading and the text underneath by placing a margin between h2

I am dealing with a situation where I have an <h2 class="landing-panel-title> containing a <span class="landing-panel-icon-right ion-ios-search-strong>. The second class on the span is from an icon font called ionicons. Despite this, it may not ...