Setting border radius for the first child of li dynamically using Javascript

I am currently working on creating a navigation bar that features rounded corners for the first and last children within an unordered list. My goal is to utilize the onclick javascript function to dynamically assign these rounded corners directly in JavaScript. Below is the snippet of code I have attempted to use. If anyone could provide insight into what may be causing issues or suggest a solution or resource, it would be greatly appreciated. Thank you in advance.

HTML:

<nav>
    <ul id="navBar">
        <li><a href="#" title="View"><div class="menu" onClick="select(this)">View</div></a></li>
        <li><a href="#" title="Duplicate"><div class="menu" onClick="select(this)">Duplicate</div></a></li>
        <li><a href="#" title="Edit"><div class="menu" onClick="select(this)">Edit</div></a></li>
        <li><a href="#" title="Delete"><div class="menu" onClick="select(this)">Delete</div></a></li>
    </ul>
</nav>

Javascript:

document.getElementById('ul#navBar li:first-child').style.MozBorderRadiusTopleft = '13px';
document.getElementById('ul#navBar li:first-child').style.MozBorderRadiusBottomleft = '13px';
document.getElementById('ul#navBar li:last-child').style.MozBorderRadiusTopRight = '13px';
document.getElementById('ul#navBar li:last-child').style.MozBorderRadiusBottomRight = '13px';

Answer №1

Your CSS stylesheet will need the following code to achieve rounded corners:

.is-rounded li:first-child {
    -moz-border-radius: 13px 0 0 13px;
    -webkit-border-radius: 13px 0 0 13px;
    border-radius: 13px 0 0 13px;
}

.is-rounded li:last-child {
    -moz-border-radius: 0 13px 13px 0;
    -webkit-border-radius: 0 13px 13px 0;
    border-radius: 0 13px 13px 0;
}

To implement this functionality using Javascript, you can use the following code:

function makeRoundedElement(e) {
   document.querySelector('#navBar').className += 'is-rounded';
}

document.querySelector('#el').addEventListener('click', makeRoundedElement, false);

In the above code snippet, it is assumed that clicking on the element with the id "el" triggers the rounded corner effect.

For a live example, you can check out the demonstration here: http://jsfiddle.net/cgrFe/3/

If you are new to this concept, I recommend starting with some foundational books such as and . The latter resource may be particularly useful for your learning journey.

Answer №2

getElementById specifically needs the id of the element for proper functionality, not a selector. If you are looking to use selectors, you may want to consider using jQuery:

$('ul#navBar li:first-child').css({
    MozBorderRadiusTopleft: '13px'
});

$('navBar li:first-child').css({
    MozBorderRadiusBottomleft: '13px'
});

$('ul#navBar li:last-child').css({
    MozBorderRadiusTopRight: '13px'
});

$('navBar li:last-child').css({
    MozBorderRadiusBottomRight: '13px'
});

Answer №3

To simplify things, I would first create two CSS classes specifically for rounded corners:

.round-top {
   MozBorderRadiusTopleft:13px;
   MozBorderRadiusTopRight:13px;
}

.round-bottom {
   MozBorderRadiusBottomleft:13px;
   MozBorderRadiusBottomRight:13px;
}

After defining these classes, you can easily add or remove them from the elements you want to style. Here's how you can do it in JavaScript:

var container = document.getElementById(navBar);
container.firstChild.setAttribute("class", "round-top");
container.lastChild.serAttribute("class", "round-bottom");

Using jQuery, the process is even simpler:

$('#navBar li:first-child').addClass('round-top');
$('#navBar li:last-child').addClass('round-bottom');

If you want to implement a full event listener, you can use the following code:

function addBorders(){
  var container = document.getElementById(navBar);
  container.firstChild.setAttribute("class", "round-top");
  container.lastChild.serAttribute("class", "round-bottom");
}

// 'target' represents the element that will trigger the event
target.addEventListener("click", addBorders, false);

Answer №4

To utilize jQuery for this task, follow these steps instead of using "border", "3px double red" and incorporate your own styles:

<script type="text/javascript" language="javascript>
         var Menu = {
            rootEl: null,

            Init: function (idRootEl) {
                this.rootEl = $(idRootEl);
                this.initItems();
                this.setFirstElSeleceted();
            },
            setFirstElSeleceted: function () {
                $($(this.rootEl).find('li')[0]).css("border", "3px double red");
            },
            initItems: function () {
                var self = this;

                $(self.rootEl).find('li').each(function (indx) {
                    $(this).click(function () {
                        self.removeSelection();
                        self.setSelected(this);
                    });

                });
            },
            setSelected: function (el) {
                $(el).css("border", "3px double red");
            },
            removeSelection: function () {
                var self = this;
                $(self.rootEl).find('li').each(function (el) {
                    $(this).css("border", "");
                });
            }
        };

        $(function() {
            Menu.Init('ul#navBar');
         });
        </script>

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

Tips for minimizing the need to copy the entire dojo library each time you create a new Java EE package for deployment on GlassFish

Currently, I am diving into comet programming and utilizing the cometd implementation along with the JavaScript dojo library before deploying my war files to GlassFish. The issue I have encountered is that every time I create a new project, I find myself i ...

Altering the dimensions of radio buttons

I am a newcomer to using material-ui. I am currently working on incorporating radio buttons in a component and would like to reduce its size. While inspecting it in Chrome, I was able to adjust the width of the svg icon (1em). However, I am unsure how to a ...

Fixing a scrolling element within a div located below the screen is my goal, ensuring it remains fixed in place as the user scrolls

I'm facing a challenge that I need help with: My HTML/CSS layout currently looks like this: Screenshot of how my CSS/HTML appears on the screen upon page load: As I scroll down, I encounter a green element: While scrolling down -> Upon further s ...

Is there anyone available who can assist me in removing records from my Sequelize database?

I attempted to implement the code snippet below after coming across it on a popular platform, but for some reason, it doesn't seem to be functioning as expected. Posts.delete({ where: { createdAt: { isAfter: "2016-09-11" } } }) My goal is to remove ...

Example of Using Python and Ajax Together: How to Send a Response using Python?

Exploring the code with Python and Javascript to set up an Ajax system. Essentially, the goal is to input a word and have the Python code send it back. Here is the HTML/JavaScript snippet: <html> <head> <title>Simple Ajax Example</tit ...

Is there a way to make the switch case condition shorter?

I need to dynamically select a text input field based on the variable type chosen, without having to include the textfield component in every single condition. const chooseInputType = () => { switch (type) { case 'boolean': ...

Text is not visible when hovering over it

I am facing an issue with the hover effect on my menu element. When I hover over the element, the text does not appear as expected. Even after using z-index to position the text on top, it still doesn't work. Here is a snippet of my code: HTML: < ...

What is the best way to stop a UL element from inheriting the height properties of a drop down menu?

My sticky navigation bar is almost finished in terms of appearance and functionality. However, I encountered an issue when adding a drop-down menu within the links – it creates an invisible field that hides nearby text. Upon investigation, I found that t ...

Combining AngularJS with Servlets: A Seamless Integration

I am attempting to retrieve a JSON object from a servlet by calling a function through a link in my HTML code. Below is the HTML link that calls the fTest function: <td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descar ...

Having issues with the JavaScript voting system {{bindings}} returning null when clicked?

It seems like the error is not appearing in the developer tool, so it might be related to how the data is being read. Both {{upVote}} and {{downVote}} start with no value and show null when clicked, indicating that the buttons are somehow linked. I was att ...

unveiling the comparison between the revealing module and object literal patterns in encapsulating code

When developing a new feature, my typical approach is to create a separate component for each one. For example, if I have a feature called abc, I would write the following JavaScript: var AbcComponent = (function(){} var initialize = function(){ }, ...

Replace the phrase "add to cart" with "plus" and "minus" in Opencart

I am trying to customize the Add to Cart functionality in OpenCart 2.0.1.1 by replacing it with plus and minus buttons. I have successfully added the plus button, however, I am facing difficulty coding for the minus button. The code snippet below shows w ...

Steps for adding products to your shopping cart without using a JavaScript framework:

As a newcomer to web development, I took on the challenge of creating an e-commerce website using only HTML, CSS, and vanilla JavaScript (without any frameworks). I've encountered a roadblock while trying to implement the "Add to Cart" functionality ...

`How can I troubleshoot path obstacles when transferring files in node.js?`

I am having trouble moving a file from an HTML form to another folder using a cloud function. I am new to both node.js and firebase, so I am unsure of what I am doing wrong. This is my current code snippet: const fileMiddleware = require('express-mult ...

Floating Ship Animation Using CSS3

I am currently working on creating a floating animation effect. The concept involves having the element swing with an axis at its lower part, similar to the image provided below: My challenge lies in figuring out how to coordinate the two movements and en ...

The process of re-rendering a component is facilitated by applying various filters

Filters are an essential feature in my application, as they help limit the output of a list of users. You can see a live example of this concept in action on my codesandbox. The functionality allows users to apply multiple filters to narrow down their sea ...

Error occurs when React-router 6 cannot render an error component

I'm facing an issue in my React app where the custom error component I created for unmatched routes is not being rendered, instead the default error page appears. Here's a snippet of how my BrowserRouter is set up: const router = createBrowserRo ...

Using AngularJS to convert a JSON object into an array

Hey there, I've got a JSON return object that looks like this: color_selected = [ { id: 4}, { id: 3} ]; Any tips on how I can convert it to the following format? color_selected = [4,3] Appreciate any help or s ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...

The virtual positioning of list items in React Virtualized

Using React Virtualized in a setup similar to the snippet provided below has raised an issue. A few items are being rendered using a CellMeasurer. The last item, which indicates that more items will be loaded, is not rendering correctly. It has the wrong p ...