When working with GWT, you can easily attach an event listener to any element on the host page

I am looking to implement a MouseOver event handler for any tag, specifically targeting anchor tags in a legacy HTML page.

Following a GWT guide, I successfully utilized their JSNI method to retrieve all anchor tags with some minor adjustments for errors.

Now, my goal is to bind all the elements collected in an ArrayList to an event handler. How can I achieve this?

Below is the code snippet that I have written:

  private native void putElementLinkIDsInList(BodyElement elt, ArrayList list) /*-{
    var links = elt.getElementsByTagName("a");

    for (var i = 0; i < links.length; i++ ) {
      var link = links.item(i);
      link.id = ("uid-a-" + i);
      <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87ebeef4f3a9c7ede6f1e6a9f2f3eeeba9c6f5f5e6fecba0ebecf7">[email protected]</a>::add(Ljava/lang/Object;) (link.id);
    }
  }-*/;

  /**
   * Find all anchor tags and if any point outside the site, redirect them to a
   * "blocked" page.
   */
  private void rewriteLinksIterative() {
    ArrayList links = new ArrayList();
    putElementLinkIDsInList(Document.get().getBody(), links);
    for (int i = 0; i < links.size(); i++) {
      Element elt = DOM.getElementById((String) links.get(i));
      rewriteLink(elt, "www.example.com");
    }
  }

 /**
   * Block all accesses out of the website that don't match 'sitename'
   * 
   * @param element
   *          An anchor link element
   * @param sitename
   *          name of the website to check. e.g. "www.example.com"
   */
  private void rewriteLink(Element element, String sitename) {
    String href = DOM.getElementProperty(element, "href");

    if (null == href) {
      return;
    }

    // We want to re-write absolute URLs that go outside of this site
    if (href.startsWith("http://")
        && !href.startsWith("http://" + sitename + "/")) {
      DOM.setElementProperty(element, "href", "http://" + sitename
          + "/Blocked.html");
    }
  }

Answer №1

If you're looking to select specific elements within a document, consider using the

Document.getElementsByTagName("a")
method. This will give you a NodeList that can be cast to AnchorElements to access the 'href' attribute.

Here is an example of how you can achieve this:

NodeList<Element> elems = Document.get().getElementsByTagName("a");
for (int i = 0; i < elems.getLength(); i++) {
  Element elem = elems.getItem(i);
  AnchorElement a = AnchorElement.as(elem);
  if (!a.getHref().startsWith("http://yoursite.com")) {
    a.setHref("http://yoursite.com/blockedpage");
  }
}

To add an event handler, you can wrap the Element in an Anchor using wrap()

for (int i = 0; i < elems.getLength(); i++) {
  Element elem = elems.get(i);
  Anchor a = Anchor.wrap(elem);
  a.addClickHandler(new ClickHandler() {
    @Override
    public void onClick(ClickEvent event) {
      Window.alert("yay!");
    }
  });
}

(If the handler will always do the same thing, consider creating one ClickHandler and adding it to all elements instead of creating a new handler for each element)

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

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

File uploading using JQuery and AJAX

An error occurred: Cannot read property 'length' of undefined I'm facing an issue with 3 file fields and their upload buttons. The problem lies in the fact that the file field is being returned as undefined. Here is the JavaScript code: $ ...

How can I use jQuery to automatically redirect to a different HTML page after updating a dynamic label?

When I click on a button in first.html, a function is called to update labels in second.html. However, despite being able to see second.html, I am unable to see the updated values in the labels. Can someone please advise me on how to achieve this? functi ...

ajax ignores output from php

I've been working on passing PHP echo values through AJAX, but I've encountered a problem where the if and else conditions are being skipped in the success function of AJAX. Even when the if condition is met, the else statements are still being e ...

Is there a way to adjust the contents of an iframe to match the dimensions of the iframe itself?

I am trying to adjust the width of an iframe to 60%, regardless of its height. Is there a way to "zoom in" on the contents of the iframe to fit the width, so that I can then set the height based on this zoom level? I haven't been able to find any solu ...

Comparing Window.Location.reload() to AJAX: Which is the better

While maintaining my GWT app, I am facing the task of refreshing a list of people once one of them has been deleted. I am currently exploring how I can send the correct AJAX request to update the list of followers. However, I am unsure whether it is appro ...

Set a delay for an AJAX request using jQuery

Is it possible to incorporate a setTimeout function into this ajax call? Here's the code snippet: jQuery.ajax({ type : "POST", url : dir+"all/money/myFile.php", data : "page="+data.replace(/\&/g, '^'), suc ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

Storing the Outcome of a mongodb Search in a Variable

I'm encountering an issue where the result of a MongoDB find operation is not being assigned to a variable (specifically, the line var user = db.collection("Users").findOne below), and instead remains undefined. I am aware that the find function retur ...

Utilizing eval properly in JavaScript

One method I am using is to load a different audio file by clicking on different texts within a web page. The jQuery function I have implemented for this purpose is as follows: var audio = document.createElement('audio'); $(".text_sample ...

The visibility of the Google +1 button is lost during the partial postback process in ASP.NET

When trying to implement the Google Plus One button using AddThis on one of our localized pages, we encountered a strange issue. Despite retrieving data from the backend (let's assume a database), the plus button was not loading during an AJAX based p ...

What is the reason behind the array.map() function not altering the original array?

I attempted to increment each element of my array by one, but was having trouble. Here is what I tried: myArray=[1,2,3] myArray.map(a=>a+=1) // also tried a++ and a=a+1 console.log(myArray) // returns [ 1 , 2 , 3 ] Unfortunately, this method did not w ...

Is it possible to select multiple drop-down lists on a webpage using Python and Selenium?

I am encountering an issue while attempting to click on multiple dropdown lists within a page. I continuously receive an error message stating that my list object does not have an attribute 'tag_name'. Here is my code snippet: def click_follow_ ...

Is there a way I can link a variable to a URL for an image?

Creating v-chip objects with dynamic variable names and images is causing an issue. The image source string depends on the name provided, but when I bind the name to the source string, the image fails to load. Despite trying solutions from a similar questi ...

What is the Angular approach for configuring a form's encoding type to application/json?

I need to send form data using a POST request that triggers a download, making it impossible to use any Javascript requests. Therefore, calling a function with the $http service is not an option. Additionally, I require the corresponding backend route in ...

Send an array and a single string to a PHP script using an Ajax request

I am attempting to incorporate the code snippet below: var flag = new Array(); var name = $("#myselectedset").val(); $.ajax({ type: 'post', cache: false, url: 'moveto.php', data: {&a ...

Retrieve 10000 sets of coordinates in real time with the help of Google Maps

I am trying to retrieve coordinates for 10,000 lines of data using the Google Maps geocoding API and display each line on the browser. My strategy involves looping through each line (which contains an address), passing it to the Google Maps URL, parsi ...

JavaScript Alert function doesn't wait for execution

I am facing an issue with my Signup page. After submitting the form, I use AJAX POST to send the data. The problem arises in the success function where an alert is triggered immediately without waiting for user input, leading to the execution of the next f ...

Exploring ways to enhance Bootstrap Navigation by adding extra link options. Seeking a resolution using jQuery

Are you looking for a solution to handle site navigation with a larger number of links? When more links are added, they display in multiple lines which might not be the desired layout. You can view an example of this issue in the attached image: See here a ...

Enable automatic profile login for the Firebase application

Imagine a web application created using Vue and Firebase. The main query revolves around automatically logging into the app after page reload, particularly accessing the database post authorization. Following user authentication, crucial data such as email ...