Add a custom Leaflet JS control button with personalized text and hover functionality

I successfully completed a control-button-leaflet tutorial and it worked for me. Now I have some additional requirements:

  1. Show some text when hovering over the button (similar to the zoom buttons)
  2. Change the button's color when hovering over it
  3. Ability to input text inside the button instead of an image.

Below is the code snippet for reference:

    var customControl =  L.Control.extend({        
      options: {
        position: 'topleft'
      },

      onAdd: function (map) {
        var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-custom');

        container.style.backgroundColor = 'white';     
        container.style.backgroundImage = "url(http://t1.gstatic.com/images?q=tbn:ANd9GcR6FCUMW5bPn8C4PbKak2BJQQsmC-K9-mbYBeFZm1ZM2w2GRy40Ew)";
        container.style.backgroundSize = "30px 30px";
        container.style.width = '30px';
        container.style.height = '30px';

        container.onclick = function(){
          console.log('buttonClicked');
        }

        return container;
      }
    });

    var map;

    var readyState = function(e){
      map = new L.Map('map').setView([48.935, 18.14], 14);
      L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
      map.addControl(new customControl());
    }

    window.addEventListener('DOMContentLoaded', readyState);

Answer №1

Instead of using a div, consider using a Button for better functionality:

    var btn = L.DomUtil.create('button');
    btn.type="button";
  1. You can easily add a mouseover text:

    btn.title="Hover over me";
    
  2. Replace an image with some Text:

    btn.value = "Click Me";
    
  3. Utilize mouse events to style the button:

    btn.onmouseover = function(){
      btn.style.backgroundColor = 'lightblue'; 
    }
    btn.onmouseout = function(){
      btn.style.backgroundColor = 'white'; 
    }
    

(Alternatively, use CSS for better styling)

See a full example here: http://codepen.io/anon/pen/yXCMzx

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's recommended to utilize the callback feature with setLoggedIn to ensure the previous state is captured effectively, as illustrated below:

To ensure capturing the previous state when using setLoggedIn, it is recommended to utilize the callback option. This will help in keeping track of changes and ensuring smoother functionality: ...

Using GraphicsMagick in combination with Node.js to upload a fresh image file to AWS S3: A step-by-step guide

I've encountered an issue while trying to upload images to S3 - phone images appear rotated due to EXIF data. To address this problem, I came across a tool called graphicsmagick which claims to remove EXIF data and resize images to 500px wide. However ...

Discovering the highest prime factor of a number using Javascript

My current focus is on creating a basic program in JavaScript that can identify the largest prime factor of an integer. Here is the code I have developed for this purpose: let result; function findFactor(number, half) { for (let i = 2; i < half; i ...

What is the technique to enable this div to be clickable?

I am trying to make each "card" of a WordPress plugin clickable on my website. I have inserted a Pure JS element with the following code: document.getElementsByClassName('fc_card-container').onclick = function() {alert('It works!');} ...

What makes this CSS causing render blocking?

I've been meticulously following the Google PageSpeed guidelines in order to optimize the performance of my website. Upon running an analysis, Google provides me with a score based on their set guidelines. There's one particular guideline that ...

The ValidationMessageFor tag is failing to function on the view page

I am currently in the process of updating the styling from bootstrap 3 to bootstrap 5. The issue I am facing is that in the bootstrap 3 version, when I click the "save" button without filling any text boxes, the page displays a validation message like this ...

Creating a dropdown menu with data loaded dynamically using ajax and json, all without relying on jquery

I am looking to populate a few select menus using JSON data retrieved from my PHP script. Each select menu should display different values based on the selections made in the other menus. While I understand how to clear and fill a select menu using JavaScr ...

Tips for creating a unique design for a form that includes a non-binary mask, inspired by bitmasks

Currently, I am in the process of creating an app using Reactjs and Material-UI. The main requirement is for users to input a mask of specific length containing various letters such as I, V, and C. In search of a suitable design pattern or solution for thi ...

The file module.js is encountering an error at line 327 because it is unable to locate the module named 'express

Hey there, I'm new to nodejs and whenever I run a file in the command prompt like:- C:\demoData>node demo.js I encounter an error like this: module.js:327 throw err; ^ Error: Cannot find module 'express' at Function.M ...

Ensuring child input components are validated upon submission using Vee-Validate and Vue.js 2

Currently, I am working on creating a Registration form with multiple "Input Field" components that require validation once the Submit button is pressed. While each input field validates individually when the text is changed, I am struggling to implement a ...

Why do I keep encountering the error of an undefined variable? Where in my code am I making a mistake

I am struggling to troubleshoot an issue with creating a simple ease scroll effect using the jQuery plugins easing.js and jquery-1.11.0.min.js. $(function(){ //capturing all clicks $("a").click(function(){ // checking for # ...

Problem with YouTube iFrame API in IE when using JavaScript

Apologies for the unclear heading, but I'm facing a peculiar issue. The YouTube iFrame API works perfectly on all browsers except Internet Explorer. In IE, none of the JavaScript code runs initially. However, when I open DevTools and refresh the page, ...

You can update a JavaScript string by adding values using the '+=' operator

I have the following function: function generateJSONstringforuncheckedfilters(){ jsonstring = ''; jsonstring = "["; $('body').on('click', 'input', function(){ jsonstring += "[{'OrderGUID&apo ...

Retrieving the value of an array from a JSON data structure

I am working with the object shown below to extract the desired output. The result will be a new object that represents the final output. var data = { Customer: { Name: "emp1", Departments: [ {Departme ...

Should one consider using requirejs to enhance individual pages instead of relying solely on vanilla JavaScript applications?

I have a question regarding the practical use of RequireJS. After learning about purely JavaScript-driven web pages, I have been enhancing individually rendered views (often provided by a PHP Framework) with AngularJS to add more functionality. However, m ...

Unable to display response following the submission of a POST request

I'm encountering an issue when attempting to display the response of a post request using node and request. While I can see the response in the console within the service, it does not make its way to the controller. Any insights on why this may be hap ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Unable to process form submission using Ajax in ASP.NET MVC

I'm having trouble with submitting a form using ajax and opening a modal dialog after the ajax function is successful. Whenever I click the submit button, the process doesn't complete. Where could the issue be, in the ajax method or somewhere el ...

Retrieving the value of a child in JSON

I have encountered this JSON structure and I am interested in extracting the value of "resource_uri" which is "/api/v1/client/2/". My implementation revolves around Backbone/javascript. Unfortunately, using json['resource_uri'] does not produce ...

The encoding for double quotation marks vanishes when used in the form action

I am attempting to pass a URL in the following format: my_url = '"query"'; when a user clicks on a form. I have experimented with encodeURI and encodeURIComponent functions as well as using alerts to confirm that I receive either "query" or %2 ...