What is the best way to apply the CssClass "active" when clicking on a link

How can we update the cssClass of a link button on each click event, considering that the page refreshes every time?

Currently, when I click on any LinkButton, the default behavior sets the cssClass to Plus LinkButton.

---index.aspx-----------

<ul class="mainMenu">
<li>
    <asp:LinkButton ID="lnkHome" runat="server"><span>Home</span></asp:LinkButton>
</li>
<li>
    <asp:LinkButton ID="lnkIndia" runat="server"><span>India</span></asp:LinkButton></li>
<li>
    <asp:LinkButton ID="lnkWorld" runat="server"><span>World</span></asp:LinkButton></li>
<li>
    <asp:LinkButton ID="lnkStates" runat="server"><span>States</span></asp:LinkButton></li>
<li>
    <asp:LinkButton ID="lnkCity" runat="server"><span>City</span></asp:LinkButton></li>
<li>
    <asp:LinkButton ID="lnkBusiness" runat="server"><span>Business</span></asp:LinkButton></li>
<li>
    <asp:LinkButton ID="lnkSport" runat="server"><span>Sport</span></asp:LinkButton></li>
<li>
    <asp:LinkButton ID="lnkMagazine" runat="server"><span>Magazine</span></asp:LinkButton></li>
<li>
    <asp:LinkButton ID="lnkBlogs" runat="server"><span>Patrika Blogs</span></asp:LinkButton></li>
<li>
    <asp:LinkButton ID="lnkPlus" CssClass="active" runat="server"><span>Plus</span></asp:LinkButton></li>


CSS Classes

ul.mainMenu{float:right; background:url(../images/menubg.gif) 0 0 repeat-x; width:100%}
ul.mainMenu li{float:left; color:#a7b5be; font-weight:bold; background:url(../images/seprator.gif) right 0 no-repeat; position:relative; z-index:999}
ul.mainMenu li a{color:#586066;line-height:24px;display:inline-block;}
ul.mainMenu li a span{color:#576067; padding:0 11px; line-height:24px; display:inline-block; }
ul.mainMenu li a:hover{background:url(../images/hover.gif) 0 0 repeat-x}
ul.mainMenu li a:hover span{color:#fff}
ul.mainMenu li a.active{background:url(../images/hover.gif) 0 -24px repeat-x;}
ul.mainMenu li a.active span{background:url(../images/redArrow.gif) center bottom no-repeat; padding-bottom:7px; color:#fff}

VB CODE

 Protected Sub lnkHome_Click(sender As Object, e As EventArgs) Handles lnkHome.Click
    If (ConfigurationManager.AppSettings("SeoFriendlyUrl") = "true") Then
        Response.RedirectToRoute("HomePage")
    Else
        Response.Redirect("index.aspx")
    End If
End Sub

Protected Sub lnkAboutUs_Click(sender As Object, e As EventArgs) Handles lnkAboutUs.Click
    ...

Answer №1

To achieve this, a combination of the link button ID and the body tag ID can be utilized effectively.

Let's use the example of the India link. The HTML code would resemble the following:

<body id="india-page">
<ul class="mainMenu">
<li>
    <asp:LinkButton ID="lnkHome" runat="server"><span>Home</span></asp:LinkButton>
</li>
<li>
    <asp:LinkButton ID="lnkIndia" runat="server"><span>India</span></asp:LinkButton></li>
<li>
</ul>

In your CSS stylesheet, you can include styles like the ones below:

#home-page ul.mainMenu li a#lnkHome {background:url(../images/hover.gif) 0 -24px repeat-x;}
#india-page ul.mainMenu li a#lnkIndia {background:url(../images/hover.gif) 0 -24px repeat-x;}

This setup ensures that any page with a 'india-page' body ID will feature the highlighted India link,

Similarly, any page with a 'home-page' body ID will showcase the highlighted home link, and so on.

Answer №2

If you're currently utilizing AspNet, consider adjusting the LinkButton attribute for every journey from the server. Alternatively, integrate it into the state so that it can be implemented after the page is refreshed.

Sincerely,

Answer №3

To trigger a jQuery function when a link button is clicked, you can implement the following script:

    <script type="text/javascript>
     $(document).ready(function () {
        $(".lnkIndia").click(function () {

            $(".lnkIndia").addClass("Name of custom CSS class");
         });

     });
    </script>

Add the above script to your page, but remember that this script is specifically for the link button with the ID 'lnkIndia'. For other buttons, you will need to create similar scripts with appropriate changes.

If you want to create a common function, you can use the following code:

  <script type="text/javascript">
   function ChangeStyle(IdOfLinkButton)
   { 
        document.getElementById(IdOfLinkButton).style.backgroundColor='blue';
        document.getElementById(IdOfLinkButton).style.border='2px solid blue';
   }
  </script>

Call this JavaScript function when a link button is clicked, and make sure to pass the ID of the link button to the function:

<asp:LinkButton ID="lnkIndia" runat="server" OnClientClick="javascript:ChangeStyle('lnkIndia');">

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

Encountering an HTTP 415 error due to an unsupported media type while accessing a Web API 2

I am in the process of updating an existing Web API 2 service by modifying one of its methods to accept a custom object as an additional parameter. Initially, the method only had one parameter which was a simple string extracted from the URL. However, upon ...

Issue with AngularJS ng-model not updating the value of a hidden input

My goal is to transmit form data using hidden input like this: <input type="hidden" required ng-model="formHolder.template[position].itemKey[itr]" ng-value="[[ formItem ]]" /> The value of formItem can be any string. Issues arise when the strings c ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Is it possible to load HTML content within a Sweet Alert pop-up

Below is the code I am using to call Swal: window.swal({ title: "Checking...", text: "Please wait", imageUrl: "{{ asset('media/photos/loaderspin.gif') }}", showConfirmButton: false, allowOutsideClick: false }); $.ajax({ t ...

Having trouble with the search function in my array, as it is consistently returning false instead of the expected result

Aim: I am working on creating a basic search bar that allows users to input a zip code and matches it with zip codes stored in an array. The objective is to develop a function that can determine whether the entered zip code exists in the array or not, and ...

Design your own custom up and down arrow icons or buttons using CSS styling techniques

Is there a way to create "up and down" control buttons using only CSS and no background image? I attempted to add CSS for arrows in "li.className:after or li.className:before", but it caused the main boxes to move. Check out the Fiddle link to see the is ...

Determine the location based on the preceding parameter of $routeChangeError using AngularJS

I am currently monitoring events of the type $routeChangeError within a run block in my application. $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) { if (!!previous) { console.log(previous); $locati ...

Manipulate a value using JavaScript

While the intention is for the button value to switch between 1 and 0, the echo $_POST["ordina"] consistently returns 1. Despite checking the code multiple times, I am unable to identify the issue. <script> function order() { if (document.ordination ...

Transferring a Variable from Arduino to JavaScript

Is there a simple way to pass an Arduino variable as a JS variable? Let's say we have an integer Arduino variable called sensorData: int sensorData = analogRead(sensorPin); How can we transfer this value to a JavaScript variable? client.println(&quo ...

Is it possible to load images top to bottom?

Is there a way to make browsers load images from the bottom to the top? Imagine I have an extremely long image that takes 60 seconds to load. The content is designed to be read from bottom to top. Is there any trick I can use to ensure that the image load ...

Function generator within a component

I have a class-based component and I need to declare a generator function for an API call inside it without using fetch.then. Below is the code snippet: class SearchField extends React.Component { componentWillUnmount() { this.props.clearSearchStat ...

What is the method for executing PHP code without the need for users to access the webpage?

Similar Query: Optimal method for running a PHP script on a schedule? I am in need of a solution where a PHP script can consistently fetch data from a single website, store it in a database on the server, and then update multiple other websites. The c ...

When PHP echo of json_encode triggers an error, AJAX status 200 will be raised

Despite everything running smoothly in the program below, an AJAX error is triggered: javascript: var data = { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026f6742656f636b6e2c616d6f">[email protect ...

Displaying the product quantity counter in the shopping cart immediately after adding the item

My website has a shopping cart quantity counter that doesn't update immediately when a product is added. Instead, it requires a page reload or navigation to another page for the change to be reflected. I would like the quantity counter to show the pro ...

Is it possible for me to invoke a div within a different component?

I am facing a challenge with a large div component. <div id='download> ..... </div> My goal is to incorporate this same component into a Paper within a Modal. <Modal> <Box sx={style} > <Paper elevation ...

What is the best way to place content in a single div without it being divided into several separate boxes

Here is my code snippet: <div class="col-md-9"> <div id="statbox"> {% for obj in product_type %} {% for obj1 in vastu %} <script type="text/javascript"&g ...

The React Native application is working fine on the emulator but is encountering some issues when trying

While the app runs smoothly on an emulator through Android Studio, I encounter an error when trying to run it from the CLI. error Failed to install the app. Ensure that you have set up the Android development environment properly: <a href="https://fac ...

Eliminate whitespace on the right side of a webpage using Bootstrap

I am currently working on a form that will appear in a modal, but I need it to be centrally aligned so that I can reduce the size of the modal. Here is what I have implemented so far: It seems like there is some space being "reserved" for columns that are ...

Encountering JSON parsing errors while using fetch() POST requests in Express

Currently, I am experimenting with HTTP requests and my main focus is on sending a POST request. The data for this request is coming from an input field and I am using fetch() to send it to a URL on my local host which is set up with express. My goal is to ...

The padding on this button seems to be arbitrary and nonsensical

I attempted to create a button with a red border that is positioned at the bottom and center, but the padding seems to be interfering with my design. It appears that with the border, the width extends to 100% which doesn't make sense. I have tried va ...