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

Navigating to a specific div within a component in Vuejs 2: Steps for routing

These are the routes I've set up for my application: const router = new VueRouter({ mode:'history', routes:[ { path:'/home', name:'home', component: Home }, { path: '/serv ...

Expand the <canvas> element to completely fill the flex item without any scrollbars

I am currently utilizing Bootstrap 5 and experimenting with setting up a nested flex layout that occupies the entire window. One of the flex items should be filled by a "stretchy" canvas element, ensuring there are no scrollbars present. However, when I a ...

How can I customize the appearance of a checkbox button in JavaFX?

I am currently working on styling a JavaFX scene with CSS in a stylesheet. The goal is to apply styles to all the "basic" elements of the scene when it loads. My issue lies in finding the correct code combination to change the background color of a button ...

Navigating a JSON array using the Handlebars template engine

I have a JSON file and I am looking for guidance on how to display the information from it using the handlebars template engine: This is the template code: <script id="template-app" type="text/x-handlebars-template"> {{#each data}} Emai ...

Use jQuery to swap out two div classes within a table cell (TD) if they are

Although I'm making progress, I must confess that jQuery and CSS are not my strong suits. The objective: To create a dynamic div within a table data cell for a calendar feature. The content of the div varies based on the date range input. A filled d ...

Overriding the Ajax URL

During an AJAX request in a Rails app triggered by onchange event, I am encountering an issue with the URL being called. The function for the request is a simple PUT operation: function quantityChange(id, val) { $.ajax({ url: 'cart_items/ ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

Browse through different states by clicking on the <a> </a> tag

Is there a way to switch between states defined by $stateProvider when clicking on the <a> </a> tag? Below are the states I have set up: $stateProvider //region page States .state('page1', { url: "/pg1", ...

Exploring the world of Javascript: The significance of variable scope and its

Encountered a unique challenge while attempting to execute an ajax call and confine the function's actions to itself. Below is the code snippet: $(document).on('click', 'input.action', function(event) { var self = this; ...

What is the best way to retrieve a value from a form and incorporate it into a controller?

Here is the code I've been working on: http://pastebin.com/AyFjjLbW I started learning AngularJS and was making progress, but now I'm facing a challenge. I'm trying to use a drop-down menu to select both a priority level and a type of job t ...

I'm still searching for a proper solution on how to access JavaScript/jQuery functions within Colorbox

For my website, I am utilizing PHP, jQuery/JavaScript, Colorbox (a jQuery lightbox plugin), Smarty, and other tools. Currently, I am working on displaying data in a popup using the Colorbox plugin. However, I am facing an issue with calling a JavaScript fu ...

Tips for utilizing JavaScript getElementByClassName to retrieve all the elements within a ul without having to specify the class name in each li

Looking to tidy up my HTML/CSS. Is there a way to keep this JavaScript functioning without needing to add the class name to every li element within the ul? Any suggestions on how to improve the visual appeal and readability of the HTML code? const Profi ...

AngularJS is not triggering the $watch function

I'm facing an issue with the $scope.$watch function, as it's not being triggered when expected. In my HTML document, I have a paginator using bootstrap UI: <pagination total-items="paginatorTotalItems" items-per-page="paginatorItemsPerPage" ...

AngularJS: Pause the data binding functionality temporarily

How can I temporarily deactivate data binding in AngularJS? I am working with a list called items that is being displayed using ng-repeat. I need to perform some operations on this list without immediately updating the page, as this could cause slowdown. ...

Techniques for retrieving elements from HTML using jQuery

I'm developing a feature that allows users to add videos to playlists by clicking on a link in a popover. The challenge I'm facing is extracting the video_id and the selected playlist when the user interacts with the popover. Any tips on how to a ...

Looking to verify the existence of a div using jQuery once other jQuery functions have executed and created HTML?

Is there a way to verify if a specific element exists within newly added HTML after clicking a button? I attempted this code snippet: $(document).on('click', '#add-html-code', function() { if ($('#something').length ...

The CSS styles are not being applied to the PHP code

I seem to have a tangled mess of CSS / PHP / HTML to deal with. The issue I'm facing is that something works on one PHP script but not the other. Here's a snippet of my code: <?php if ($daten->getData_DB_User($get_page_num) != fa ...

``There seems to be an issue with the jquery swipe function not allowing navigation through elements in the

As I work on redesigning a website to optimize it for mobile devices, I wanted to incorporate swipe left and right navigation. After some research, I came across a jQuery example that seemed promising: Upon implementing this solution on my site, everythin ...

Interactions between JavaScript and PHP scripts within a web application

THE SCENARIO In the midst of creating a web application that dynamically loads content by fetching data from a MongoDB database where items and their respective authors are stored in separate collections within the same database. The author's ID is s ...

Using asynchronous functions in React Native still generates a promise despite the presence of the 'await' keyword

After making an API call, my react-native component is supposed to return some SVG. Despite using an async function with await, the function still returns a promise that has not resolved yet. I have seen similar questions asked before, but I am puzzled as ...