Tips on adding a local image to a button

In my JavaScript file, I have buttons that look like this:

var myButton = $('<button type="button" style="display:inline">Translate Right</button>');
    myButton.css({"margin-top":"5px", "float":"left"});

Now, I want to replace the text "Translate Right" with an icon. Here is what I tried:

   var myButton = $('<button type="button" style="display:inline">Translate Right</button>');
       myButton.css({"margin-top":"5px", "float":"left"});
       $('body').append(myButton); 
      myButton.html('<img src="path\to\image">'); // backslash because I'm using windows

Unfortunately, this approach is not working. The button is empty and I receive an error saying "Not allowed to load local resource." I attempted changing "url" to "src" but it did not solve the issue. The button remains empty.

For reference, I successfully replaced the text with a different image from . However, I'm still facing difficulties in loading the local image.

If you could provide some guidance or assistance, I would greatly appreciate it. Thank you.

Answer №1

To enhance the design, I would use a pseudo element. You can find more information about this technique here: http://css-tricks.com/pseudo-element-roundup/

Additionally, I suggest avoiding placing CSS styles within your JavaScript code. Instead, consider changing the class name using JavaScript. This approach is explained in detail here:

For example:


.myButton:after{
  content: '';
  display: inline-block;
  width: 20px;
  height: 20px;
  background: url(myIcon.png);
}

Edit:

It seems like there may be an issue in your code after trying different things. The JSFiddle provided in this link works correctly for me: http://jsfiddle.net/4C6e3/

Answer №2

If you're looking for a solution, consider the following approach:

let newBtn = $('<button type="button" style="display:inline">Move Right</button>');
newBtn.css({"margin-top":"5px", "float":"left"});

Then proceed with:

newBtn.html('<img src="path/to/icon" />');

However, it's recommended to utilize <button> in this scenario...

JSBin Demo

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

It is important for the action to be able to identify dynamic objects within an {{#each}} iteration

I have a function linked to a specific list item that is being iterated multiple times, and I want this function to identify the corresponding list item. Here is the code snippet for the function. I mistakenly used this.$() thinking it would work with all ...

Unable to display api results in React using console.log

I'm having an issue with my console log not displaying the API results. Can someone help me figure out what's wrong? I'm new to React, so any guidance would be appreciated. componentDidMount() { this.setState({ loading: true }) cons ...

Problem with Jquery Ajax, failing to recognize option values

Hello everyone, please review the code snippet below... $.fn.myajax = function (options) { var defaults = { my_event: "", my_url: "", my_data: "", } var o = {}; var mydata = options.my_data; $.extend(o, default ...

Leverage the power of HTML, CSS, and Bootstrap within Visual Studio 2022 when developing with

Could someone help me figure out how to implement HTML, CSS, and JavaScript design in Visual Studio 2022 while utilizing ASP.NET controls for coding purposes? I am encountering difficulties in starting my work on a website project. Any assistance would be ...

I encountered an error in JavaScript where the function .val() is not recognized on the selected answer, throwing

I'm trying to verify if the selected answer is correct and then add +1 to my user score. However, I'm struggling with why my code isn't functioning as expected. Can someone please point out where the bug is or if there's something else ...

Populate an empty object by listening for an event in AngularJS

Using my service, I trigger the event using $rootScope.$emit. In the controller, I listen for this event and store the passed data in an array. This allows me to display the values using the ng-repeat directive. When the service function is called, it add ...

Visualizing data in Angular js using JSON Object

I am currently working on implementing chart representation in AngularJS. While I have successfully implemented simple charts, I now need assistance with converting the below JSON data into arrays for chart representation: [{"value": {"DE":2,"NP":20,"BD" ...

Stop auto-scrolling to the top when triggering a getJSON request

I'm feeling really puzzled at the moment. Here is the snippet of code I am struggling with: $("#combinations").on("change", "input", function (e) { e.preventDefault(); console.log(e) var $button, $row, $group, $form, $barcode ...

What are the issues with the latest API routing in Next.js?

I am encountering an error that says: SyntaxError: Unexpected token s in JSON at position 0 Here is my code: import { PrismaClient } from '@prisma/client'; import { IDPay } from 'idpay'; import { NextResponse } from 'next/server&ap ...

Attempting to address the issue of aligning items within a flexible div container

I seem to be encountering a recurring issue in my code. Here is an example: <div className="flex flex-col w-full mb-3"> <div className="flex flex-row w-full"> { Vege && <p className="mr-1 ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

Show just a trio of pagination figures from the overall collection in Javascript

I have been working on implementing pagination numbers in JavaScript. While I have managed to achieve pagination and display all the numbers, I am looking to show only three numbers out of all the available numbers. Here's what I have accomplished so ...

Create a unique custom React component by exporting an npm component

In my common.js file, I am trying to gather components that I have installed via npm. Here is what I have tried: import 'dropdown-group/style.css' // this works fine export 'dropdown-group' But it doesn't seem to work. I also a ...

Is it possible for me to display multiple sources in EJS?

I am working on incorporating data from two separate sources onto a single HTML page using EJS, JavaScript, and Node.js. Here is what I have tried so far: app.set('view engine', 'ejs'); app.get('/', function(req, res) { res ...

Unveiling the Secret: Empowering a Span to Secure its Territory Amidst an Adv

I have a comment section header where I want the senders name(s) (on the left) and time (on the right) to align at the top. <div style="float:left;">John Doe, Suzie Q</div><span class="pull-right"> Jan 30 at 10:29 PM</span> On s ...

Utilizing regular expressions on a URI parameter in JavaScript

I implemented an ajax function that retrieves three images (PORTRAIT, SQUARE, and LANDSCAPE) from a JSON response: $.ajax({ url: link, method: 'GET', headers: { "Authorization": authToken ...

Encountered a VUE error stating "Cannot use 'in' operator to search for 'path' in undefined". This issue led to an infinite loop, prompting me to search for solutions on StackOverflow and other similar forums. More details can be found

I am currently using this demo for learning purposes. If you want to see the full code, you can visit my GitHub repository here: https://github.com/tNhanDerivative/nhanStore_frontEnd and access my domain: vuestore.nhan-thenoobmaster.com. The error I am exp ...

Can we create an onFullscreen event handler for Power Bi Embedded?

I am currently working on creating a Report Component using React. I am looking to implement a functionality similar to the on() function in order to set up an event listener for when the report enters fullscreen mode. This way, I can pass a Function via ...

How can I identify the blur or focusout event in a tinyMCE textarea?

I have been tackling with an existing project. Whenever I click on some editable text within the webpage, it transforms into a textarea and shows the tinyMCE toolbar. However, when I click outside of that textarea, the toolbar disappears. I am trying to fi ...

Is there a way to automatically highlight an input field upon page load?

Is there a way for certain websites to automatically highlight an input field upon entering a page? For instance, YouTube's login page automatically highlights the Username field as soon as you land on it. Even this site, particularly on the Ask Ques ...