Mystery of the Unresponsive MD Ripple Button

While working on creating a CSS button, I wanted to incorporate the Material Design ripple or wave effect into it. I came across a simple script on codepen that works well by adding the class "ripple" to various elements such as divs, buttons, images, and links. However, I encountered an issue where it would not open the link associated with the button I had created. As someone who isn't very experienced in jQuery or JavaScript, I suspect that this problem might be related to the JS code. The link opens fine when the "ripple" class is removed from the button, but the button fails to function properly in launching the link when the class is added even though the ripple animation works perfectly.

I would appreciate any guidance on resolving this dilemma. You can find the codepen demo I'm using here.

I understand your explanation that it may need to be one or the other, but I'm a bit confused about the best approach. I managed to make the link open in the original or "same" window by eliminating the target="_blank", but I was hoping to retain the target option without both tabs opening the new link if possible.

(function (window, $) {

  $(function() {


$('.ripple').on('click', function (event) {
  window.location = $(this).attr('href');
   /* event.preventDefault(); */

/*HTML Button Code*/
<div class="media__body tagline overtext"><a href="http://www.google.com" class="media-btn-bottom-blue ripple" target="new">Learn More</a></div>

Answer №1

Thank you ochi for highlighting the solution - make sure to delete line

window.location = $(this).attr('href');
in your code.

For a practical demonstration, you can check out this link: http://codepen.io/anon/pen/ZOYrmx (By clicking on the login button on the left, Google should open in a new tab)

Answer №2

By including the line event.preventDefault();, the default behavior of the link is stopped.

To further enhance the click handler, consider adding this code snippet at the end:

window.location.href=$(this).data('href'); // **

** It is assumed that the link contains a data-href attribute, like in the example below:

<a href="#" data-href="http://www.google.com"class="ripple" >Login</a>

$(function() {
  $('.ripple').on('click', function(event) {
    event.preventDefault();

    var $div = $('<div/>'),
      btnOffset = $(this).offset(),
      xPos = event.pageX - btnOffset.left,
      yPos = event.pageY - btnOffset.top;

    $div.addClass('ripple-effect');
    var $ripple = $(".ripple-effect");

    $ripple.css("height", $(this).height());
    $ripple.css("width", $(this).height());
    $div
      .css({
        top: yPos - ($ripple.height() / 2),
        left: xPos - ($ripple.width() / 2),
        background: $(this).data("ripple-color")
      })
      .appendTo($(this));

    window.setTimeout(function() {
      $div.remove();
    }, 2000);

    //add this
    alert($(this).attr('href'));

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="media__body tagline overtext">
  <a href="http://www.google.com" class="media-btn-bottom-blue ripple" target="_blank">Learn More</a>
</div>

Answer №3

Inspired by Craig Tuttle's CodePen project, I have enhanced it to support fixed position buttons by incorporating the ripple-fixed class to the element. Additionally, I have updated it to ES6 so that it can be easily imported and used as an external module.

const bindRipples = () => {

  $('.ripple').on("click", event => {
    event.preventDefault()

    let $this = $(event.currentTarget)
    let $div = $('<div/>')
    let btnOffset = $this.offset()
    let xPos
    let yPos

    $div.addClass('ripple-effect')
    let $ripple = $(".ripple-effect")

    $ripple.css("height", $this.height())
    $ripple.css("width", $this.height())

    if(!$this.hasClass('ripple-fixed')) {
      xPos = event.pageX - btnOffset.left
      yPos = event.pageY - btnOffset.top

      $div.css({
        top: yPos - ($ripple.height()/2),
        left: xPos - ($ripple.width()/2),
        background: $this.data("ripple-color")
      })

    } else {
      xPos = event.clientX - $this.offset().left
      yPos = event.clientY - $this.offset().top + $('body').scrollTop()

      $div.css({
        background: $this.data("ripple-color"),
        top: yPos,
        left: xPos,
        position: 'absolute'
      })
    }
    $div.appendTo($this)

    window.setTimeout(() => {
      $div.remove();
    }, 4000)
  })
}

module.exports = bindRipples

Credit goes to Craig Tuttle for the original script available at http://codepen.io/Craigtut/pen/dIfzv. I have made necessary adjustments to make it compatible with fixed position elements and converted it to ES6 syntax.

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

Filtering data in Asp.net MVC 3 and converting it to JSON format

For my asp.net mvc 3 project, I'm considering the best approach for handling data: should I pass all the data via JSON and filter it with JavaScript, or should I filter the data first and then convert it to JSON? If filtering the data before passing ...

If the width is divisible by a certain value

I have a question regarding the width of my element that I want to divide by 90. If this width is a multiple of 90, I set the width of the element. If not, I move on to the next. For example, when the window width is 1000px and the element is at full widt ...

The middleware is causing disruptions in the configuration of redis and express

I've recently started using Redis and I'm facing an issue with my middleware 'cache' function that seems to be causing problems in my code. Everything works fine without it, the data displays correctly in the browser, and when I check f ...

Distributing JWT to the recipient using Express

Allow me to provide you with an overview of my application, which is quite straightforward. The main concept revolves around a user inputting their accountname and password into an html form on the /Login page like so: <form action="/Login" m ...

Displaying numerous information panels on Google Maps by extracting data from MySQL

Help needed! I've been struggling with this code for a while now. I can show multiple markers on the map but can't figure out how to display info details in a pop up box when they are clicked. Currently, I'm just trying to make it say "Hey!" ...

Difficulty encountered in getting html email signature to appear correctly on Outlook

I have developed a personalized email signature using HTML. Here's the unique code: <html> <!-- Insert your company logo here --> <div id="far_left" style="width: 50px; height: 50px; float: left; ...

Utilizing AJAX POST requests from JavaScript to a Rails 4 controller while implementing Strong Parameters

As a newcomer to Rails, I am looking to insert song_id and title received from JavaScript via AJAX POST into a MySQL database. In my JavaScript file: var song_id = "23f4"; var title = "test"; $( document ).ready( function() { jQuery.ajax({ ...

Tips for integrating Redux toolkit with the latest version of Next.js

It seems that in order to incorporate redux into my app, I must enclose the majority of it within a redux provider, which should be a client component. As a result, almost every part of my app becomes a child of this client component. Does this imply tha ...

Achieving consistent alignment for text on a curved path

I am working on a unique "flow-builder" project and I need to achieve this specific result: At the moment, my current edge looks like this: The text on the edge is currently aligned with the edge itself, however, I need it to align differently as shown i ...

Can we leverage Angular service styles in scss?

I am working on a change-color.service.ts file that contains the following code snippet: public defaultStyles = { firstDesignBackgroundColor: '#a31329', firstDesignFontColor: '#ffffff', secondDesignBackgroundColor: '#d1 ...

PHP ajax handling multiple requests

I've searched high and low on the internet, but couldn't find a solution to my problem. I am making multiple jQuery AJAX calls to a PHP script. Initially, I noticed that each call was being executed only after the previous one had finished. To a ...

Program does not display the expected alert message when using if/else statement

I'm grappling with creating a basic program that accomplishes the following: Develop a function declaration named changePowerTotal which accepts: The total current power generated (a numeric value) A generator ID (a number) The new status of ...

Trouble with displaying days on the Datepicker

I'm currently facing an issue with my datepicker. I have a specific set of days that should be highlighted on the calendar, and it needs to be constantly updated. For example, past days are removed from the calendar automatically to keep it current. H ...

Obtain the child's identification number and include it in the parent element as an ARIA

I need assistance with a JavaScript (or jQuery) function to dynamically add an 'aria-labelledby' attribute to parent <figure> elements based on the ID of the <figcaption>. I have multiple images and captions set up in <figure>&l ...

Discovering ways to showcase JSON response in JavaScript or PHP

Currently, I am integrating the Coin Warz API into my website. The API sends responses in JSON format. I have attempted to display this data in a table format using PHP, but unfortunately, I am encountering difficulties. The JSON Response is as follows: [ ...

What is the accurate user agent for Windows Phone?

Can someone explain why PHP and JavaScript produce different user agents? Which one is considered the accurate user agent? PHP User Agent Output: <?php print_r($_SERVER['HTTP_USER_AGENT']); ?> User Agent: Mozilla/5.0 (Mobile; Windows Ph ...

Oops! Looks like you forgot to include the "reducer" argument. It is necessary and should be either a function or an object of functions that can be passed to combineReducers

1 I'm currently working through the Redux tutorials on their website and I'm encountering an issue when trying to use combine reducers. When I run my code without using combine reducers, everything works fine. However, as soon as I include the s ...

I am in need of a datepicker for my project that will display the END date as the current date and set the START date as 7 days before the END date

$(document).ready(function () { $("#end").datepicker({ dateFormat: "dd-M-yy", minDate: 0, onSelect: function () { var start = $('#start'); var startDate = $(this).datepicker('getDate') ...

CSS Navigation Bar Fails to Function Properly on Mobile Devices

Check out the plunkr I have created by visiting: http://plnkr.co/edit/gqtFoQ4x2ONnn1BfRmI9?p=preview The menu on this plunkr functions correctly on a desktop or laptop, but it doesn't display properly on a mobile device. I suspect that the issue may ...

What is the benefit of using an IIFE in this particular way when constructing a JavaScript library?

Many libraries I've seen use a similar style to define their structure. Upon further inspection, I've noticed that the first self-invoking function is often related to Require.js or AMD systems, with 'factory' as an argument. My curiosi ...