Is it possible to create a single code that can be used for various buttons that perform the same function?

Whenever I click the right button, the left button appears and when I reach the last page, the right button disappears. However, this behavior is affecting both sections. Is there a way to write separate code for each section?

I managed to make it work by using different IDs but that approach is not ideal. It becomes a coding problem if I have more than 10 rows.

Can this be achieved with jQuery?

HTML

<section>
  <div class="left" id="links"><div>
  <div class="right" id="rechts"><div>
</section>
<section>
  <div class="left" id="btn-l"><div>
  <div class="right" id="btn-r"><div>
</section>

CSS

#links {
    text-align: center;
    width:50px;
    height: 100px;
    border: 1px solid red;
    position: absolute;
    left: 10px;
    top: 145px;
    z-index: 100;
}
#rechts {
    text-align: center;
    width:50px;
    height: 100px;
    border: 1px solid red;
    position: absolute;
    right: 10px;
    top: 145px;
    z-index: 100;
}
#btn-l {
    text-align: center;
    width:50px;
    height: 100px;
    border: 1px solid red;
    position: absolute;
    left: 10px;
    top: 310px;
    z-index: 100;
}
#btn-r {
    text-align: center;
    width:50px;
    height: 100px;
    border: 1px solid red;
    position: absolute;
    right: 10px;
    top: 315px;
    z-index: 100;
}

Jquery

var page1 = 0;
$('.left').hide();
$('.right').click(function(){
  $('.left').show();
  page1+= 1;
  if(page1 >= 3) {
    $('.right').hide();
  }
});
$('.left').click(function(){
  page1-=1;
  if(page1<3){
    $('.right').show();
  }
  if(page1 == 0){
    $('.left').hide();
  }
});

Answer №1

Perhaps in this way:

let buttonCount = 10;
  let page = 0;

  function displayButtons(){
    if(page === 0){
      $('.left').hide();
    } else {
      $('.left').show();
    }
    if(page === buttonCount - 2){
      $('.right').hide();
    } else {
      $('.right').show();
    }
   }

   $('.but').click(function(){
    if($(this).hasClass('left')){
      page--;
    }
    if($(this).hasClass('right')){
      page++;
    }
    $('#output').html('This is page '+ (page + 1) +' out of '+ (buttonCount - 1) ); /* for testing purposes */
    displayButtons();
   });

    $('#output').html('This is page '+ (page + 1) +' out of '+ (buttonCount - 1) ); /* for testing purposes */
    displayButtons();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <button class="but left">left</button>
  <button class="but right">right</button>

<div id="output"></div>

  <button class="but left">left</button>
  <button class="but right">right</button>

Option two (for multiple divs):

function displayButtons(_el){
    let currentOutput = $(_el).parent().find('.output');
    let currentPage = parseInt(currentOutput.attr('page'), 10);
    let count = parseInt(currentOutput.attr('count'), 10);

    if(currentPage === 0){
      $(_el).parent().find('.left').hide();
    } else {
      $(_el).parent().find('.left').show();
    }
    if(currentPage === count-2){
      $(_el).parent().find('.right').hide();
    } else {
      $(_el).parent().find('.right').show();
    }

    currentOutput.html('This is page '+ (currentPage + 1) +' out of '+ (count - 1) );
}

$('.but').click(function(){
    let currentOutput = $(this).parent().find('.output');
    let currentPage = parseInt(currentOutput.attr('page'), 10);
    let count = parseInt(currentOutput.attr('count'), 10);

    if($(this).hasClass('left')){
        currentPage--;
    }
    if($(this).hasClass('right')){
        currentPage++;
    }
    currentOutput.attr('page', currentPage);
    displayButtons(this);
});

$('.output').each(function(){
    displayButtons(this);
});
span{
  width:200px;
  border-style:solid;
  border-width:1px;
  display:inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div>
 <span>
   <button class="but left">left</button>
   <button class="but right">right</button>
   <div page="0" count="10" class="output"></div>
   <button class="but left">left</button>
   <button class="but right">right</button>
 </span>
 <span>
   <button class="but left">left</button>
   <button class="but right">right</button>
   <div page="3" count="8" class="output"></div>
   <button class="but left">left</button>
   <button class="but right">right</button>
 </span>
</div>

Answer №2

If you want to experiment further, consider attempting the following:

<div onclick="myFunction(this)">Up</div>
<div onclick="myFunction(this)">Down</div>
<script>
function myFunction(elmnt) {
  //Modify elements based on your preferences
}
</script>

Answer №3

To gain a better understanding of javascript objects, I suggest starting with the following code snippet:

// This script contains information about different pages using javascript objects
const movin = [ { pageMax: 10, page: 3, ID_left: 'links', ID_Right: 'rechts' }
              , { pageMax: 7, page: 2, ID_left: 'btn-l', ID_Right: 'btn-r' }
              ];

$('.left, .right').click(function()
  {
  let ref
    , elmID = $(this).attr('id')
    ;
  if ($(this).hasClass('right'))
    {
    ref = movin.findIndex(e=>e.ID_Right === elmID );
    movin[ref].page++;
    }
  else
    {
    ref = movin.findIndex(e=>e.ID_left === elmID );
    movin[ref].page--;
    }

  console.clear();
  console.log('page=', movin[ref].page ,'/', movin[ref].pageMax );

  $('#'+movin[ref].ID_left).css('visibility', (movin[ref].page===0)?'hidden':'visible' );
  $('#'+movin[ref].ID_Right).css('visibility', (movin[ref].page===movin[ref].pageMax)?'hidden':'visible' );
  })
div { display: inline-block; padding: .3em .7em; border: 1px solid grey; margin: 1em; cursor: pointer;}
div:hover { background-color: coral; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <div class="left" id="links"> left 1</div>
  <div class="right" id="rechts">right 1</div>
</section>
<section>
  <div class="left" id="btn-l"> left 2</div>
  <div class="right" id="btn-r"> right 2 </div>
</section>

Answer №4

If you're trying to access the specific div within the same section, you can achieve this by using the following code snippet in your event handler:

var section = $(this).closest("section");

You can then locate the left and right buttons within this section, for example:

var left = section.find(".left");

Instead of using $(".left"), utilize left which will refer to the button specifically within that section.

Here's an example demonstrating this approach:

var maxPage = 3;

$(".left").click(function() {
  var section = $(this).closest("section");
  var page = section.find(".page").text() * 1;
  page--;
  if (page < 1)
    page = 1;
  section.find(".page").text(page);
  $(this).attr("disabled", page == 1);
  section.find(".right").attr("disabled", false);
});

$(".right").click(function() {
  var section = $(this).closest("section");
  var page = section.find(".page").text() * 1;
  page++;
  if (page > maxPage)
    page = maxPage;
  section.find(".page").text(page);
  $(this).attr("disabled", page == maxPage);
  section.find(".left").attr("disabled", false);
});

$(".left").attr("disabled", true);
.left,
.right {
  border: 1px solid green;
  cursor: pointer;
}

.left[disabled],
.right[disabled] {
  border: 1px solid red;
  cursor: not-allowed;
}

section {
  clear: both;
}

section>div {
  float: left;
  width: 50px;
  margin: 5px;
  text-align: center;
}

section+section {
  border-top: 1px solid #CCC
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <div class="left">left</div>
  <div class='page'>1</div>
  <div class="right">right</div>
</section>
<section>
  <div class="left">left</div>
  <div class='page'>1</div>
  <div class="right">right</div>
</section>

To reduce redundancy, consider merging multiple left clicks and right clicks into separate functions after the initial step of accessing the relevant section.


Additionally, it is recommended to use

<button type='button class'left'>left</button>

instead of a <div> for better click handling, especially in scenarios involving double-clicks or text selection.

Answer №5

Set a common class for the buttons and add a single click function to that class after the page has finished loading, as shown below:

$(document).ready(function(){
$(".alertButton").click(function(){
alert("clicked!");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="alertButton">Click me 1</button>
<button class="alertButton">Click me 2</button>
<button class="alertButton">Click me 3</button>
<button class="alertButton">Click me 4</button>
<button class="alertButton">Click me 5</button>
<button class="alertButton">Click me 6</button>
<button class="alertButton">Click me 7</button>
<button class="alertButton">Click me 8</button>
<button class="alertButton">Click me 9</button>
<button class="alertButton">Click me 10</button>

Answer №6

var sections = {s1:0,s2:0};
$('.left').hide();
$('.right').click(function(){
  var sectionId = $(this).parents('section').attr('id');

  $('.left').show();
  sections[sectionId] = sections[sectionId]+1;
  if(sections[sectionId] >= 3) {
    $('#'+ sectionId +' .right').hide();
  }
});
$('.left').click(function(){
var sectionId = $(this).parents('section').attr('id');
  sections[sectionId] = sections[sectionId]-1;
  if(sections[sectionId]<3){
    $('#'+ sectionId +' .right').show();
  }
  if(sections[sectionId] == 0){
    $('#'+ sectionId +' .left').hide();
  }
});
<section id="s1">
  <div class="left"><div>
  <div class="right"><div>
</section>
<section id="s2">
  <div class="left"><div>
  <div class="right"><div>
</section>

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

Inquiring about the usage of div elements in constructing an HTML webpage

When designing my own web pages, I consistently encounter issues with using divs for a multi-column layout. Despite utilizing the float attribute to align columns left or right, resizing the browser window often causes them to stack on top of each other an ...

Next.JS CSS modules are experiencing issues with functionality

Organizing the CSS structure for a project by creating a module of CSS for each component or page can sometimes present challenges. Take a look at the code snippet below: .navbar { display: flex; justify-content: flex-start; align-items: center; pa ...

What is the correct way to test setInterval() statements within Angular?

Here is a simple code snippet I am working on: public async authenticate(username: string, password: string) { const authenticationResponse = await this.dataProvider.authenticate(username, password); if (authenticationResponse.result.code == 0) { ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

Tips on how to link images in an HTML file when it is being accessed locally on a host server

I am working on creating an HTML file that displays an image. My plan is to package the project into a zip folder and share it with someone who will run it on their local machine. Assuming I have an index.html file that includes an image called infographi ...

The synchronization between Typescript and the HTML view breaks down

I am currently working on an application that retrieves user event posts from MongoDB and displays them in HTML. In the Event-post.ts file, inside the ngOnInit() function, I have written code to retrieve the posts using the postsService.getPosts() method. ...

Challenge with Expect.js validation in a lesson on Codeacademy

I am currently developing a lesson on Codecademy to teach users about the construction of HTML forms. This project is mainly for my own enjoyment, just to keep everyone in the loop. After reviewing the submission test guidelines and API, I made the decisio ...

Is the javascript function I created not recognized as "a function"?

A small .js file containing 3 functions for easy in-site cookie management was created. Below is the source code: // Create Cookie function Bake(name,value) { var oDate = new Date(); oDate.setYear(oDate.getFullYear()+1); var oCookie = encodeURIComponent(n ...

Make necessary changes to empty objects within a JSON array

Modify the null objects in a JSON array. I attempted to use map, but it did not update all the JSON objects. Here is an example of a JSON array: var response = { "code": null, "message": "Total 1 records found", "result": { "ordersList": [ ...

In Bootstrap 4, the positioning of :after is different compared to Bootstrap 3

Our bootstrap nav-tabs have a unique default look with an 'indicator' icon below the selected tab. This is achieved by styling the active anchor element as follows: https://i.sstatic.net/UQos5.png However, when migrating to bootstrap 4, we noti ...

Closing the nested accordion will collapse all sections within the accordion

I'm currently facing an issue with my nested accordions. I've been attempting to nest them in a way that doesn't require writing additional jQuery code for each new one added. As an example, I've created a jsfiddle... https://jsfiddle. ...

What's the best way to retrieve the dates for the current week using JavaScript?

Could anyone help me find a way to retrieve the first and last dates of the current week? For example, for this week, it would be from September 4th to September 10th. I encountered an issue at the end of the month when dates overlap two months (such as t ...

Attempting to save MongoDB data into a variable for integration with Handlebars.js

Having an issue with storing MongoDB data in a variable to display in HTML using hbs. The specific error message is TypeError: Cannot read property 'collection' of undefined. Here's the code snippet I have written: const express = require(& ...

Using $.ajax to make asynchronous requests in ASP.NET Web Forms

I am currently working on incorporating the $.ajax method into my sample program. The structure of the page is as follows: <form id="form1" runat="server"> <div> Country: <asp:TextBox ID="txtCountry" runat="s ...

React is up and running smoothly on my local machine, but unfortunately encountering issues on Vercel

I have encountered an issue while trying to deploy my website on Vercel. Despite the build logs showing a successful compilation, I am receiving a "failed to compile" error: [16:43:24.951] Running build in Washington, D.C., USA (East) – iad1 [16:43:25.05 ...

jQuery $.ajax problem encountered

When working with AngularJS, we have the ability to catch errors using the $http() service as shown below: return $http(defaultConfig).then(sendResponseData)**.catch(errorCallBack)**; On the other hand, when attempting to do something similar in jQuery: ...

Center align for drop-down menu

I'm currently working on styling an asp:DropDownList element using custom CSS. I have successfully set the height, but I am facing a challenge with getting the text to align in the middle of the element rather than at the bottom. The vertical-align:mi ...

Ways to adjust the size of a Primeng autocomplete with multiple selections?

I'm new to Angular and I'm attempting to adjust the width of a primeng auto complete component in order to fill the column of a table. I've already experimented with using style="width: 100%" but that approach hasn't yielded any result ...

Steps for creating a Foundation 6 accordion

Can anyone assist me in creating a Foundation 6 accordion? I tried to follow the code from the documentation, but it's quite confusing. I seem to be missing something and can't figure out what. Here is the HTML code from the docs: <ul class= ...

Is ngSwitch in Angular causing the label element to disappear?

I am using AngularJS to generate form elements dynamically based on an array containing form details such as input type and value. For example, here is the code snippet I have for creating a text input field: <div ng-repeat="input in input_array"> ...