The JQuery code restricts the use of multiple buttons within a single instance

UPDATE

I am facing an issue where I am trying to add the same set of buttons inside multiple divs, however, it seems that the button set only appears in one div at a time. I want the button set to show up in every location where I place it. Here is the code I am using:

    (function($){

// jQuery plugin creation:
$.fn.sweetPages = function(opts){

    // Create an empty opts object if no options were passed
    if(!opts) opts = {};

    var resultsPerPage = opts.perPage || 3;

    // Best suited for unordered lists, but ordered lists would work too:
    var ul = this;
    var li = ul.find('li');

    li.each(function(){
        // Calculate the height of each li element and store it using the data method:
        var el = $(this);
        el.data('height',el.outerHeight(true));
    });

    // Calculate the total number of pages:
    var pagesNumber = Math.ceil(li.length/resultsPerPage);

    // Do nothing if there are less than two pages:
    if(pagesNumber<2) return this;

    // Create the controls div:
    var swControls = $('<div class="swControls">');

    for(var i=0;i<pagesNumber;i++)
    {
        // Slice a portion of the lis, wrap it in a swPage div:
        li.slice(i*resultsPerPage,(i+1)*resultsPerPage).wrapAll('<div class="swPage" />');

        // Add a link to the swControls div:
        swControls.append('<a href="" class="swShowPage">'+(i+1)+'</a>');
    }

    ul.append(swControls);

    var maxHeight = 0;
    var totalWidth = 0;

    var swPage = ul.find('.swPage');
    swPage.each(function(){

        // Loop through all the newly created pages:

        var elem = $(this);

        var tmpHeight = 0;
        elem.find('li').each(function(){tmpHeight+=$(this).data('height');});

        if(tmpHeight>maxHeight)
            maxHeight = tmpHeight;

        totalWidth+=elem.outerWidth();

        elem.css('float','left').width(ul.width());
    });

    swPage.wrapAll('<div class="swSlider" />');

    // Set the height of the ul to the height of the tallest page:
    ul.height(maxHeight);

    var swSlider = ul.find('.swSlider');
    swSlider.append('<div class="clear" />').width(totalWidth);

    var hyperLinks = ul.find('a.swShowPage');

    hyperLinks.click(function(e){

        // Slide the swSlider div and mark the clicked link as active:

        $(this).addClass('active').siblings().removeClass('active');

        swSlider.stop().animate({'margin-left':-(parseInt($(this).text())-1)*ul.width()},'slow');
        e.preventDefault();
    });

    // Mark the first link as active:
    hyperLinks.eq(0).addClass('active');

    // Center the control div:
    swControls.css({
        'left':'50%',
        'margin-left':-swControls.width()/2
    });

    return this;

}})(jQuery);


$(document).ready(function(){
    /* This code is executed once the DOM is loaded */

    // Splitting the #holder UL into pages of 3 LIs each:
    $('#holder').sweetPages({perPage:1});

    // Moving the page links to the main container instead of the ul:
    var controls = $('.swControls').detach();
    controls.appendTo('#main');

    // Create Navigation Buttons

    function goToPage(page){
    $('.swShowPage:contains("' + page + '")').click();
}

var baseFB = '<input type="button" class="swFB" />';
var offset = 'pgOffset';
var active = '.swShowPage.active';

var $pgBack = $(baseFB)
    .attr('id', 'button_back')
    .attr('value', "Back")
    .attr(offset, '-1');

var $pgForward = $(baseFB)
    .attr('id', 'button_forward')
    .attr('value', "Next")
    .attr(offset, '1');

$.each([$pgBack, $pgForward], function(i,$obj){
    $obj.click(function(){
        var nextPage =  parseInt($(active).text(), 10) + parseInt($(this).attr(offset), 10);
        goToPage(nextPage);
    });
});


$($pgForward).addClass("teach_create_backforward");
$($pgBack).addClass("teach_create_backforward");

$('.teach_create_pageheader_back').prepend($pgBack);
$('.teach_create_pageheader_forward').prepend($pgForward);


});

The HTML:

<li>
    <div class="noselect" id="teach_create_pageheader">
        <span id="teach_create_pageheader_back"></span>
        Step 1
        <span id="teach_create_pageheader_forward"></span>
    </div>
</li>
<li>
    <div class="noselect" id="teach_create_pageheader">
        <span id="teach_create_pageheader_back"></span>
        Step 2
        <span id="teach_create_pageheader_forward"></span>
    </div>
<li>
    <div class="noselect" id="teach_create_pageheader">
        <span id="teach_create_pageheader_back"></span>
        Step 3
        <span id="teach_create_pageheader_forward"></span>
    </div>
<li>

Answer №1

It is crucial that each element ID is unique on a single page.

Is this the information you were looking for? http://jsfiddle.net/haER9/2/

Make sure to register your click events in the following manner

$(".button_forward").click(function(){alert("forward");})
$(".button_back").click(function(){alert("back");})

Answer №2

According to the jQuery API documentation (refer to http://api.jquery.com/id-selector/)...

It is essential for each id value to be unique within a document. If multiple elements are given the same ID, queries targeting that ID will only return the first matching element in the DOM.

It is advisable to avoid reusing identifiers and opt for using classes instead.

Here is an example (not guaranteed to work as provided, but illustrates the concept)...

<li>
    <div class="noselect" id="teach_create_pageheader1">
        <span class="teach_create_pageheader_back"></span>
        Step 1
        <span class="teach_create_pageheader_forward"></span>
    </div>
</li>

$('.teach_create_pageheader_back').prepend($pgBack);
$('.teach_create_pageheader_forward').prepend($pgForward);

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

The Mystery of Two Nearly Identical Functions: One function is queued using Queue.Jquery, but the effects fail to work on this particular function. What could be causing this

In short, I am currently working on my first portfolio where I am utilizing Jquery to manipulate text. My goal is to have the text fade in and out sequentially. However, when using the queue function to load another function, the text within the span tag ...

Tips for centering a div horizontally when it exceeds the width of a mobile screen

My challenge is to create a circular div element that is wider than the mobile screen and perfectly centered. This circular div needs to be an exact circle, specifically targeted for mobile screens. I've attempted to achieve this using the code in th ...

Discovering the initial element with a data attribute above zero using JQuery

I am working with a set of divs that have the class .item-wrap. At the moment, I am able to select the first div using this code snippet: $(".item-wrap:first").trigger( "click" ); Each .item-wrap element comes with a data-amount attribute. My challenge ...

Sliding off the canvas - concealed navigation

I have implemented CSS to hide a menu on mobile: #filter-column { position:absolute; left:-400px; } However, I want the menu to slide in from the left when the user clicks a link, and everything else should be hidden. When the layer is closed, th ...

Having trouble with nested confirm pop ups?

I am attempting to show an additional confirmation pop-up when the YES button is clicked, but it doesn't seem to be working. Here's my code: $.confirm({ text: "Are you sure you want to delete ?", confirm: function() { $.confirm( ...

Improve the design of the email newsletter

Having some trouble coding a particular element in my email newsletter layout. This is the desired outcome: View Screenshot Here's what I currently have: View Screenshot Any idea what could be going wrong here? Check out the code snippet below: &l ...

What is the best strategy for positioning an anchor element within a list item using JSX or Bootstrap in a way that maximizes efficiency?

I have the following code snippet <li className = "list-group-item list-group-item-success" key ={todo.id}>{todo.text}<a style="float:right;" onClick={() => props.onEdit(todo)} className="edit-todo glyphicon glyphicon-edit" href="#"& ...

Creating a specific ng-init condition for introducing new elements into the scope

Using ng-repeat, I am generating a series of todo items within div elements. My goal is to automatically apply the "editing = true" styling to these newly created items and if possible, focus on them as well. <div class="item" ng-class="{'editing- ...

Previewing multiple file inputs: extracting individual IDs for each one

After attempting to implement a multiple file selection input with previews, I discovered that IE does not support it. As a result, I have modified my approach to a multiple file upload by using multiple single file inputs, each with its own corresponding ...

Transforming the initial character of a label element into uppercase

When I receive an external HTML page, all the data comes in lowercase. I attempted to capitalize the first letter of each label tag using CSS, but it ended up making the entire text uppercase instead. Here is what I tried: .fontmodal { text-transform ...

Personalized jQuery Slider with automatic sliding

I am currently working on creating my own image slider without relying on plugins. 1st inquiry : How can I achieve horizontal animation for the slider? 2nd inquiry : I want the images to cover both the height and width of their container while maintainin ...

Arrange content within DIVs using Bootstrap-4

I'm having trouble figuring out how to align and organize my div content using Bootstrap. I'm a bit confused about how it all fits together align-items- * text-* align-self- * justify-items- * justify-self- * I'm attempting to structure my ...

Comparison between Filament Group's loadCSS and AJAX technologies

The loadCSS library developed by Filament Group is widely recognized as the standard for asynchronously loading CSS. Even Google recommends its use. However, instead of using this library, some suggest utilizing ajax to achieve the same result. For example ...

Changes in an image element's transition can result in either resizing or shifting positions

When I apply an opacity transition to an img element as shown here, I notice that the size of the image changes or it appears to move at the start and end of the transition. Below is a simple CSS code for styling: img{ height:165px; width:165px; ...

Automated vertical alignment of rows within the Bootstrap table

I'm currently working on a table for my personal project that populates with data from the database. I am trying to get the rows to display vertically under headings (see screenshot at the bottom of this question). I have attempted various solutions f ...

Carousel position images off-center to the right on smaller screens

I created a fullscreen slider using the carousel bootstrap feature. However, when the screen size shrinks, the background image resizes and centers itself. Instead of centering the image on smaller screens, I want it to focus on the right side. Here is ho ...

OptinMonster's innovative feature - the Pardot form with an inline button

Having trouble integrating an HTML Pardot form into OptinMonster's floating footer option. I'm looking to align all three fields inline, along with the button. Can anyone assist me in placing the button inline with the fields? HTML: <fo ...

Ways to transmit information from a PHP server to a client

I am diving into the world of web technology and I'm attempting to send data from a PHP server to a client test.html. However, only alert("1") is displayed and alert("2") is not printing as expected. My goal is to display JSON data in the alert(JSON.s ...

Issue with pagination functionality post-Ajax request on Rails platform

I am working on implementing pagination using the Kaminari plugin. As I Ajaxify my application, I have run into an issue. I have a form that contains paginated data along with another form used for filtering that data (both work via Ajax). Initially, the p ...

The React sidebar expanded to cover the entire screen width

As I work on creating a dashboard page that will display a sidebar after the user logs in, I am facing an issue where the sidebar is taking up the full width of the page, causing my Dashboard component to drop to the bottom. You can view the image link of ...