Using Javascript, you can create a function that can disable or enable a text link based on

Here is the code snippet showcasing CSS styles and HTML elements:

CSS:


.enableLink{
font-family:Verdana, Geneva, sans-serif;
font-size:12px;
color:#069;
padding-right:20px;
text-decoration:underline;
cursor:pointer;
}
.disableLink{
display:none;
font-family:Verdana, Geneva, sans-serif;
font-size:12px;
color:#069;
padding-right:20px;
text-decoration:underline;
cursor:default;
}
.btnToPage {
background-color:#ededed;
border-radius:6px;
border:1px solid #dcdcdc;
display:inline-block;
color:#7c7c7c;
font-family:Arial;
font-size:15px;
font-weight:bold;
padding:6px 24px;
text-decoration:none;
text-shadow:0px 1px 0px #ffffff;
cursor:default;
}

.btnToPage:active {
position:relative;
cursor:pointer;
}

.myButton {
-moz-box-shadow:inset 0px 1px 0px 0px #bbdaf7;
-webkit-box-shadow:inset 0px 1px 0px 0px #bbdaf7;
box-shadow:inset 0px 1px 0px 0px #bbdaf7;
background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #79bbff), color-stop(1, #378de5));
background:-moz-linear-gradient(top, #79bbff 5%, #378de5 100%);
background:-webkit-linear-gradient(top, #79bbff 5%, #378de5 100%);
background:-o-linear-gradient(top, #79...

HTML:


<span class="enableLink">Enable</span> 
<span class="disableLink">Disable</span>
<div id="btnNext" class="btnToPage">Go to page 2</div>

When implementing this code using JavaScript for better functionality, there are areas that need improvement. Below is the JavaScript part:


$(document).ready(function(){ 
// JS Enable
$(".enableLink").click(function(){  
// Enable Button Go to page 2
$("#btnNext").removeClass("btnToPage").addClass("myButton");
$(".enableLink").hide();
$(".disableLink").show().css({"cursor":"pointer"});
});
// JS Disable
$(".disableLink").click(function(){ 
// Disable Button Go to page 2
$("#btnNext").removeClass("myButton").addClass("btnToPage");
$(".disableLink").hide();
$(".enableLink").show();
});
// Redirect to another page?
$(".myButton").click(function(){
window.open("page2.html", target="_self");
});
});

Two questions arise from here: how to implement an "if else" condition in the 'JS Enable' and 'JS Disable' sections, and how to create a correct redirect link once the 'myButton' class is active in the 'enableLink' section. The existing code does not navigate to the next page as intended, so any guidance on fixing the redirection would be greatly appreciated.

Check out the example in JSFiddle: https://jsfiddle.net/kw5nyx4f

Answer №1

You have the opportunity to simplify things significantly...

$('span').on('click', function() {
    $("#btnNext").toggleClass("myButton");
    $(this).toggle();
    $('span').not(this).toggle();
  });
  
  $("#btnNext").on('click', function(){
      if ($(this).hasClass('myButton')) {
window.location.href = 'http://www.example.com';
        } else {
          //Insert click on disabled function here, if any.
          }
});
body { margin: 40px; }

.enableLink{
font-family:Verdana, Geneva, sans-serif;
font-size:12px;
color:#069;
padding-right:20px;
text-decoration:underline;
cursor:pointer;
}
.disableLink{
display:none;
font-family:Verdana, Geneva, sans-serif;
font-size:12px;
color:#069;
padding-right:20px;
text-decoration:underline;
cursor:default;
}
.btnToPage {
background-color:#ededed;
border-radius:6px;
border:1px solid #dcdcdc;
display:inline-block;
color:#7c7c7c;
font-family:Arial;
font-size:15px;
font-weight:bold;
padding:6px 24px;
text-decoration:none;
text-shadow:0px 1px 0px #ffffff;
cursor:default;
}

.btnToPage:active {
position:relative;
cursor:pointer;
}
.myButton {
-moz-box-shadow:inset 0px 1px 0px 0px #bbdaf7;
-webkit-box-shadow:inset 0px 1px 0px 0px #bbdaf7;
box-shadow:inset 0px 1px 0px 0px #bbdaf7;
background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #79bbff), color-stop(1, #378de5));
background:-moz-linear-gradient(top, #79bbff 5%, #378de5 100%);
background:-webkit-linear-gradient(top, #79bbff 5%, #378de5 100%);
background:-o-linear-gradient(top, #79bbff 5%, #378de5 100%);
background:-ms-linear-gradient(top, #79bbff 5%, #378de5 100%);
background:linear-gradient(to bottom, #79bbff 5%, #378de5 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#79bbff', endColorstr='#378de5',GradientType=0);
background-color:#79bbff;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
border:1px solid #84bbf3;
display:inline-block;
cursor:pointer;
color:#ffffff;
font-family:Arial;
font-size:15px;font-weight:bold;padding:6px 24px;text-decoration:none;text-shadow:0px 1px 0px #528ecc;
}
.myButton:hover {
background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #378de5), color-stop(1, #79bbff));
background:-moz-linear-gradient(top, #378de5 5%, #79bbff 100%);
background:-webkit-linear-gradient(top, #378de5 5%, #79bbff 100%);
background:-o-linear-gradient(top, #378de5 5%, #79bbff 100%);
background:-ms-linear-gradient(top, #378de5 5%, #79bbff 100%);
background:linear-gradient(to bottom, #378de5 5%, #79bbff 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#378de5', endColorstr='#79bbff',GradientType=0);
background-color:#378de5;
}
.myButton:active {
position:relative;top:1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="enableLink">Enable</span> 
<span class="disableLink">Disable</span>
<div id="btnNext" class="btnToPage">Go to page 2</div>

Simply assign the active class to toggle instead of using remove/addClass; this is what the toggle function is designed for.

I modified the click event to simply toggle the visibility of the spans. This eliminates the need to specify which span was clicked. jQuery automatically detects the clicked element and can apply actions to other similar unclicked elements.

Additionally, I adjusted the button click to target the ID rather than the class. It checks if the button is active and, if so, redirects to the specified URL.

Depending on other elements in the markup, exclusively targeting the generic span for the click event may or may not pose an issue. If required, you can give both spans the same class and then target the class instead of each individual span.

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

Having difficulty customizing the color of bullet points within a list

I've been attempting to update the color of the list points without success. Can you help me troubleshoot? <div class="mobile-menu" id="mobile-menu"> <div id="mobile-menu-links"> <h4>General:</h4> ...

jQuery locates all elements with a specific class after all other elements

I am working with multiple dynamically generated divs that share the same class. The amount of these divs can vary, so I do not have a fixed number in advance. My goal is to insert an additional div after the last one in the sequence. <div class="some ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

"Automatically close the fancybox once the form is confirmed in the AJAX success

Having an issue with closing my fancybox after submitting the registration form on my website. I am using the CMS Pro system.... Here is how I display the fancybox with the form: submitHandler: function(form) { var str = $("#subscriber_application"). ...

Troubleshooting problem with navigation tabs in Bootstrap version 3.x

My bootstrap component nav-tabs works fine on desktop when the page width is larger than necessary for the row. However, on mobile devices, the responsive design doesn't behave as expected and the tabs become misaligned. You can see the issue in the c ...

Issue with setting multiple checkboxes in AG Grid

I have a situation where I am trying to select multiple checkboxes on different rows in my application. Each time I click on one checkbox, it gets selected just fine. However, when I click on another checkbox in a different row, the previously selected che ...

Page Loading Issue: Unable to Process Ajax POST Request

I am facing an issue with my form that uses Ajax to send data to a PHP file. Everything seems to be working fine as the data sends properly, but I keep getting an "Error loading page" message when using jQuery Mobile. HTML File <div data-role="page" i ...

What are the steps to run and test the renovate bot on your local machine

Before setting up renovate to work with my Azure pipeline, I wanted to test it locally using npx renovate to ensure everything is working as expected and that my config file is properly configured. I ran npx renovate --platform local command. My project i ...

My jquery filter is not functioning properly

I need help making the active class work on each category when clicked, shifting to the next one. I've tried implementing it but no luck so far. $(document).ready(function() { $('.list-inline-item').click(function() { const value = ...

Implementing X.PagedList within a modal pop-up window

I have implemented a modal pop-up on a webpage: ... <div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="companySearchModal" aria-hidden="true" id="companySearchModal"> <div class="modal-dialog" role="document"> ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

Adjust the positioning of two divs on mobile devices

My website has two main divs, one on the left and one on the right. The left div is styled with the classes: col-md-3 left_side And the right div with: col-md-9 right_side In the CSS file, the left_side and right_side classes only have padding, without a ...

Setting the default <a-sky> in Aframe: A step-by-step guide

There was a fascinating projection I witnessed where two images were displayed in the sky. [https://codepen.io/captDaylight/full/PNaVmR/][code] Upon opening it, you are greeted with two spheres and a default white background. As you move your cursor over ...

Exploring the intricacies of XML embedded within JSON

Utilizing YQL for jQuery, I am able to successfully execute cross-domain REST requests. The JSON response contains the desired XML data as key-value pairs. The specific request being made is: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%2 ...

Is AJAX causing issues with updating the ASP.NET Core MVC view accurately?

My application is built using ASP.NET Core 6 MVC. I have a table on a page where I want to enable drag and drop functionality for its rows. After rearranging the rows, users can click on "Submit" to make the changes permanent. Once submitted, the changes ...

Utilize typehead.js in Python Django to retrieve an updated data list directly from the database

file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a ...

Chrome Automatically Playing WebRTC Audio

My webapp has webrtc functionality, but I've noticed a strange issue. When connections are established between Chrome browsers, the audio is not played, while video is. However, this problem doesn't occur with Mozilla users. So... Chrome user 1 ...

Tips for streamlining the transfer of essential features from a main project to its duplicate projects

In my Angular project, I have a core repository on GitHub that serves as the foundation for custom client projects. Each time a new client comes onboard, we create a clone of the core project and make customizations based on their requirements. The issue ...

Ways to Press the Enter Key on Different Browsers

Looking for a solution to get the keypress action working properly? I have a chat feature where I need to send messages. Here is what I have in the Form-tag (JSP based): function SendMessage() { if (event.keyCode===13) { ale ...