Implementing a function on various pages using the pagebeforeshow event handler in jQuery

I am facing an issue with the execution of the pagebeforeshow command in my webapp. I have built a webapp consisting of three html5 pages (page1, page2, and page3.html) with similar structures.

page1.html

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height">
<title></title>

<link rel="stylesheet" href="css/jquery.mobile-1.3.2.css" type="text/css">

<script src="js/jquery-1.9.1.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/app.js"></script>

<style type="text/css">
    body {
        width:100%; 
    }

    #mainBtn, #helpBtn, #backBtn {
        width:50px;
        height:10px;
        padding:2px 10px 10px 10px;
        color:#FFF;
    }

    #contentBox {
        width:80%;
        height:500px;
        margin:15px auto;   
    }

    #page1 #contentBox {
        background-color:aqua;
    }

    #page2 #contentBox {
        background-color:yellow;
    }

    #page3 #contentBox {
        background-color:grey;
    }
</style>

</head> 
<body> 

<div data-role="page" id="page1">   
<div data-role="header" data-position="fixed" data-theme="b">
     <a id="mainBtn" href="page2.html" data-transition="slide" data-inline="true"></a>
     <h3>page 1</h3>
     <a id="helpBtn" href="page3.html" data-transition="slide" data-inline="true"></a> 
</div><!-- /header -->

<div data-role="content">
    <div id="contentBox">
        Some Content Here
    </div>
</div><!-- /content -->

<script type="text/javascript">
    $(document).on('pagebeforeshow', '#page1',  function() {
        addBtnText();
    });

</script>

 </div><!-- /page -->

 </body>
 </html>

Page2.html

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height">
</head> 
<body> 

<div data-role="page" id="page2">   
<div data-role="header" data-position="fixed" data-theme="b">
     <a id="backBtn" href="page1.html" data-transition="slide" data-direction="reverse"></a>
     <h3>page 2</h3>
     <a id="helpBtn" href="page3.html" data-transition="slide" data-inline="true"></a> 
</div><!-- /header -->

<div data-role="content">
    <div id="contentBox">
        Some Content Here
    </div>
</div><!-- /content -->

<script type="text/javascript">
    $(document).on('pagebeforeshow', '#page2',  function() {
        addBtnText();
    });

</script>

 </div><!-- /page -->

</body>
</html>

Page3.html

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height">
</head> 
<body> 

<div data-role="page" id="page3">   
<div data-role="header" data-position="fixed" data-id="etHdr" data-theme="b">
     <a id="backBtn" href="page1.html" data-transition="slide" data-direction="reverse"></a>
     <h3>page 3</h3>
     <a id="mainBtn" href="page2.html" data-transition="slide" data-direction="reverse"></a> 
</div><!-- /header -->

<div data-role="content">
    <div id="contentBox">
        Some Content Here
    </div>
</div><!-- /content -->

<script type="text/javascript">
    $(document).on('pagebeforeshow', '#page3',  function() {
        addBtnText();
    });

</script>

</div><!-- /page -->

</body>
</html>

Moreover, I have an app.js file that includes the addBtnText() function.

App.js

function addBtnText() {
// Update button text
$("#backBtn").html('back');
$("#mainBtn").html('main');
$("#helpBtn").html('help');
}

In theory, the expectation is to run the addBtnText function before each page loads to add text labels to buttons. The function works correctly on page1, partially on page2 (loads back button text only), and doesn't work at all on page3 (no back or main button text).

This inconsistent behavior has left me puzzled as to why it works fine on page 1 but not on page 2 and entirely fails on page 3.

Is there something crucial missing in the splitting of the pages and calling of functions?

Thank you for your assistance!

Answer №1

After some troubleshooting, I finally discovered the root of my issue - and Omar's advice was spot on. It turns out that the problem stemmed from an ID conflict, caused by my traditional web page mindset conflicting with jQuery's method of loading pages into the DOM. By switching the problematic IDs to classes on the buttons, everything fell into place just as anticipated.

A big thank you to Omar for pointing me in the right direction!

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

What are some strategies for preventing the $window.alert function from being triggered within an AngularJS controller's scope?

How can I prevent the alert from appearing on my dashboard? Do you have any suggestions? Thank you! I attempted to override the alert empty function in my controller, but I am still encountering the window alert when I navigate to my page. $window.alert ...

What is the best way to incorporate width adjustments in an image source for a responsive website?

Currently learning CSS and experimenting with it on an HTML page. For reference, I'm using this link. Encountering an issue with a responsive header image that adjusts size based on device (small on mobile, large on desktop). Is it possible to achiev ...

Creating a right-aligned glyph within a Panel header using Bootstrap

I am currently designing a Panel using bootstrap and I would like to include a glyph in the heading, aligned to the right. I tried adding "text-right" to the span tag but unfortunately, it didn't work as expected. Here is the code snippet: < ...

How can I update the language of a button text in a React component?

Looking to update the button labels from a different language to English. Here is how it currently appears: https://i.sstatic.net/6JZ6m.png ...

Event listener is failing to execute the functions

Even though the inline onmouseover="verdadero()" function is properly set up Upon further inspection, it appears that while the event listener is added to the box element, the function is not being triggered when hovering over it, and console.lo ...

Is it possible to stop the onchange event while it is already running?

I am working with 2 bootstrap 5 multi-select dropdown lists that both contain the same information. The requirement is that if an option is selected in one dropdown, it cannot be selected in the other. I understand that this may not be the ideal scenario, ...

Splitting with Regex - One Time Operation

Here is some of my Jquery code along with Regex: $("[class^=ipsum-img],[class^=ipsum-img-]").each(function(){ var x = $(this).attr("class"); console.log(x.length); if (x.length>8) { var m = x.split(/(\d+)[^-]*$/g); cons ...

When the React-bootstrap Popover arrow is oriented vertically, the arrow colors appear to be inverted compared to when it

Utilizing a react-bootstrap Popover component, I have implemented custom styling for the arrow with a gray color and 50% opacity. The CSS code that enables this customization is as shown below: .popover .popover-arrow::before, .popover .popover-arrow::afte ...

Showing an image in a Bootstrap Modal using data fetched from an ajax json response

My current issue involves displaying and editing a record from a database using Bootstrap modal. Everything works fine except for the image rendering - it doesn't seem to display the edited image. While an HTML dataType renders the image correctly, I ...

Creating a sidebar that remains fixed in place even as the page is scrolled down can be achieved by using CSS and positioning properties

I am looking to create a website with a specific layout design as shown in this image: https://i.stack.imgur.com/ndKcz.png The main focus is on making the sidebar (F/T container) function as a social network link, sticking to the right side of the page ev ...

How to Create a Floating DIV with CSS

Here is the URL I am referring to: Website I want to position the Weather DIV above other content on the page while still maintaining its position when expanded or collapsed. How can I achieve this without affecting the layout of other elements? This is ...

Unleashing the Power of the "OR" Operator in Form Field Validation

The custom JavaScript function FormQuote_Validator is used to validate form fields. It should return the value "TRUE" and display an alert message if all three input fields are submitted without any numbers; otherwise, it should return the value "FALSE". ...

Having troubles with PHP retrieving images from my server directory over here

My current code is designed to retrieve an image from my server and display it on my HTML page. However, the images are stored in an encrypted format using MD5 and do not have corresponding names in the table. To fetch the image, I am using the primary key ...

Guide on how to smoothly navigate through an HTML page to a specific anchor point

Is there a way to use JavaScript to make the browser scroll the page to a specific anchor? In my HTML code, I have set either a name or id attribute like this: <a name="anchorName">..</a> or <h1 id="anchorName2">..&l ...

Choosing versatility over specificity when dealing with web API routes

Hey there! I'm a beginner when it comes to web API routes and I've encountered an issue where my call is choosing the more general route instead of the specific one. The AJAX call I am using is: $.getJSON("/api/solutions/GetSolutionByCategory ...

What is the reason for object destructuring not functioning properly in styles?

Why is it that the HTMLelement is considered an object, while the style is also an object, yet this code fails to work as expected? When I remove destructuring, everything functions properly, so I am curious to understand the underlying reason behind thi ...

Is it possible to create a basic textarea with minimal height-rows but fill 100% of the height?

Within my div, there is a textarea element that I am having trouble sizing correctly vertically. The container div is set to the right size (100%), but I need to give the textarea a minimum height or number of rows to enable scrolling if needed, while sti ...

When the mouse hovers, the background image of <ul> <li> tabs will disappear

I have a simple set of HTML tabs using <ul> and <li> elements with some custom CSS styles. You can view the code on jsfiddle here. Each tab follows this structure (for more details, please refer to the linked code): ... <li class="icon ...

Ways to move upward from a lower position

I am trying to create a hover effect where the title and content move to the right position upon hovering. The issue I am facing is that the transition on the `Title` class is not working, and as a result, the hover effect is also not functioning properly ...

Locate a Checkbox using JQuery and NodeJS

Searching for the presence of a checkbox in a webpage using NodeJS with JQuery (other suggestions are welcome). However, I am struggling to locate the checkboxes within the form. Below is the code snippet from the webpage: <form id="roombookingform" c ...