What are some recommended techniques for utilizing Anchors within HTML?

As someone new to web development, I'm curious about the best practices for using anchors in HTML design. Right now, I am creating a list where users can click on list items (li) and then perform a specific action using jQuery. Additionally, I have some images acting as clickable buttons, but I'm unsure if it would be better practice to use anchors instead.

Answer №1

If you are looking to redirect from one webpage to another, it is recommended to utilize an anchor tag. However, if you wish to incorporate event handling, it will depend on the markup structure.

Typically, writing inline JavaScript or CSS code is not considered a good practice. Instead, it is advised to use classes or IDs and write custom code in a separate JavaScript file.

For instance:

<ul id="primary-nav">
  <li> Home </li>
  <li> About </li>
</ul>

After adding jQuery to your page, you can implement the necessary code as follows:

(function(){
  $("#primary-nav").on("click", function(){
    // Your Code;
  })
})

Here are some examples of best practices:

HTML boilerplate

<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible"/>
    <title>Your Page Title</title>
    <meta name="description" content="goes here..."/>
    <meta name="keywords" content="keyword 1, keyword 2"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
    <meta name="robots"/>

    <link rel="stylesheet" href="your-single-deployment-stylesheet.css">
    <link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon-72x72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon-114x114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="apple-touch-icon-144x144-precomposed.png">
    <!-- JS Links should sit on the bottom of the page! -->
</head>
<body>
... content
<script src="yourJavascript.js"></script>
</body>
</html>

CSS

Example of code with poor naming conventions

.s-scr {
  overflow: auto;
}
.cb {
  background: #000;
}

Example of code with improved naming conventions

.is-scrollable {
  overflow: auto;
}
.column-body {
  background: #000;
}

Example of code with poor names

.right-red {
  float: right;
  color: red;
}

Example of code with better names

.text-highlight {
  float: right;
  color: red;
}

JavaScript

//avoid repeating var in variable declaration
var foo;
var bar;
var lorem;
var ipsum;

//comma seperated variable declarations
var foo,
    bar,
    lorem,
    ipsum;

Avoid defining in multiple steps

var foo = {};

foo.prop = 'bar';

foo.method = function() {};

//defined in a single assignment
var foo = {   
  prop: 'bar',    
  method: function() {}
}

To prevent global namespace pollution, consider using the following snippet:

(function( window, undefined ) {
  var foo = 1; //private variable

})( window );

Check out my other posts on GitHub for more insights on best practices at www.github.com/ananddeepsingh

Answer №2

Give this a shot, it's incredibly straightforward using the 'onclick' event in JavaScript. It can be applied to any element within the Document Object Model (DOM).

For example:

<button onclick="alert('Hello, world!')">Click me</button>

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

Creating an infinite products loader using ajax can be a great way to enhance the

I have encountered a challenging issue that I am struggling to overcome, partly due to my unfamiliarity with the correct terminology. As a newcomer to this field, please forgive the clumsiness of my question. Below is an outline of my objective: Currentl ...

Ways to activate Bootstrap using our javascript

http://getbootstrap.com/javascript/#buttons? They have provided a demo for radio button toggling in Bootstrap. I attempted to implement it in my code, but the active state is not switching. What could be causing this issue? CDNs I am using: Code input ...

Determining the post_thumbnail's dimensions by force

How can I maintain a constant image size for post thumbnails on my website, regardless of the original image's dimensions? I attempted to achieve this using the following code: <?php if (has_post_thumbnail()) the_post_thumbnail(array(400, 200)); ...

Generate a standard Wordpress menu containing all pages without the need to manually add each page in the menu editor

I'm struggling to figure out how to display all pages in WordPress without manually adding them to a menu. Instead of creating a new menu and selecting specific pages, I want to automatically show all existing pages in the menu. For example, if I ha ...

Challenges associated with Bootstrap toggle switch

I am having some difficulties with using bootstrap switch. I have tried the examples provided on , but regardless of the classes I apply, the buttons remain the same small size and the text for ON and OFF is barely visible. I can't seem to figure out ...

Tips for positioning Bootstrap thumbnail elements

I have a query regarding my implementation of the thumbnail feature in Bootstrap. My goal is to ensure that three thumbnails are aligned per row. Refer to the image linked below for clarification: This is the desired layout: (Click Here) The image illust ...

Is it possible to validate link clicks and integrate PHP within JavaScript functions?

Before anyone mentions security concerns, please refrain. Imagine I have an index.php. This page contains several links to 'home.php', each with different data stored in the href attributes. For example: Link 1: 'home.php?data=1&count ...

Customizing vertical padding in Bootstrap 4 Tables: Adjusting the spacing between rows

<div class="table-wrapper"> TABLE STUFF </div> I'm using Bootstrap to create a table with no borders, but I'm finding that the rows have too much vertical padding. How can I adjust the padding to create a more compact design? ...

What is the best way to create these types of Layouts in blade.php?

Check out the code snippet provided below. click here for image description <div class="container-fluid"> <div class="row"> <div class="col-sm-8 col-md-8"> </div> ...

Accessing the form element in the HTML outside of the form tag in Angular 2

I am attempting to achieve the following: <span *ngIf="heroForm?.dirty"> FOO </span> <form *ngIf="active" (ngSubmit)="onSubmit()" #heroForm="ngForm"> <div class="form-group"> <label for="name">Name</label& ...

How to prevent users from selecting an item using jQuery UI Selectable

Having the following HTML layout, I want to prevent the user from selecting a specific item with a data-attribute value when they enter 'a,' 'b,' or 'c' into the text box (#txtprevent). For example, if 'b' is entere ...

Elements within the Div are perfectly aligned in the center and restricted from moving to either the left or right edges of the

Currently, I am developing a project similar to Gmail. In order to achieve this, I need to design a div container that consists of various components such as Inbox, Send, Draft, etc. However, when I attempt to move these components around, the icons disapp ...

Is Webkit's Overflow Scrolling feature hiding the divs on your website?

I recently implemented a design for my website where the content is contained within an absolute positioned div that takes up the entire screen. However, I noticed that the scrolling on this div felt clunky and not as smooth as I would like it to be. After ...

What is the best way to incorporate easing into your scroll animations for a polished

Looking for a way to enhance the smooth scrolling effect in my script, I decided to experiment with adding easing: $('a[href*="#"]') .not('[href="#"]') .not('[href="#0"]') .click(function(event) { if ( locatio ...

Unable to utilize the rupee font within a select element on Chrome and IE8 browsers

Issues with displaying rupee font in select element on Chrome and IE8 I have implemented WebRupee for showing the Indian currency symbol. The font appears correctly when used within a <p> tag, but when placed inside a select option element, it only ...

Reducing the size of an internal label within a flex container

Hello everyone, I could really use some assistance here. The problem I'm facing involves a flex-container with tabs (the number of tabs can vary as they are passed as an array in a React component). Each tab consists of a label and a span with a numb ...

Extracting updated dom elements with a query

Within my HTML document, I have a div section containing various form input elements. Using jQuery('#div').html(), I can retrieve the original content of this section. However, when I make changes to the form inputs by entering text or selecting ...

Prioritize returning AJAX data over iterating through the parent loop

Hey everyone, I'm having trouble wrapping my head around this issue even after researching various scenarios online. Here's what's going on: I have an array of strings named recipientsList. What I want to do is make an AJAX call for each s ...

How can I create an animation effect that shows and hides slides using jQuery?

Looking for help to implement a slide effect on a simple steps page. Currently facing an issue with the strange behavior of the sliding effect. When the div enters, it momentarily appears under the previous div instead of coming out smoothly. Here's ...

Navigating through the DOM hierarchy and deleting a class

Having multiple forms on a single page, each with its own validation error message box and close button, has presented a challenge. While I can successfully close the message box using the close button, removing the "error" class from the specific text inp ...