Adding HTML elements to a button using an array: a step-by-step guide

In the process of developing a web application feature using JavaScript, I have come up with a simple plan:

  1. Place a button in the bottom left corner.
  2. The button should only become visible after scrolling begins.
  3. Upon clicking the button, a new window will open to display a PDF file.

Currently, I have managed to implement this on individual pages, but it's becoming too burdensome. The code snippet below shows how it works:

// JavaScript Document
$(document).ready(function(){
//added this for DW
'use strict';
$('#ap1').append('<div id="formInstructions" class="btn btn-aprs"><span class="fa fa-question-circle"></span>&nbspForm&nbspInstructions</div>');
$(window).scroll(function () {

//the original funtion was != 0
if ($(this).scrollTop() !== 0) {
$('#formInstructions').fadeIn();
} else {
$('#formInstructions').fadeOut();
}
});
$('#formInstructions').click(function(){
window.open("../static/instructions/ap2_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
return false;
});
});
#formInstructions {
position: fixed;
bottom: 10px;
left: 10px;
cursor: pointer;
display: none;
}
<!-- this is in element in the HMTL file -->

<div id="ap1">&nbsp;</div>

This is an example screenshot from an individual page:

My ultimate aim is to create a single script to automate this process throughout the entire application. Below is my initial attempt at making this happen:

<script type="text/javascript">
      var arr = [ "#ap1", "#ap2", "#ap3", "#ap4", "#ap5", "#ap6", "#ap7", "#ap8", "#ap9", "#ap10", "#ap11", "#ap12", "#ap13", "#ap14", "#ap15", "#ap17", "#apa", "#apb", "#apc", "#apd", "#ape", "#apf, "#apg", "#aph", "#api", "#apj", "#apk", "#apl", "#apm", "#apn", "#apo", "#app, "#apq" ];

      $(document).ready(function(){
        jQuery.each( arr, function( i, val ) {
          $(arr).append('<div id="formInstructions" class="btn btn-aprs"><span class="fa fa-question-circle"></span>&nbspForm&nbspInstructions</div>');

          $(window).scroll(function () {
            //the original function was != 0
                if ($(this).scrollTop() !== 0) {
                    $('#formInstructions').fadeIn();
                } else {
                    $('#formInstructions').fadeOut();
                }
            });
          if (arr == '#ap1') {
            $('#formInstructions').click(function(){
                    window.open("../static/instructions/ap1_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
                    return false;
          } else if (arr == '#ap2'){
            $('#formInstructions').click(function(){
              window.open("../static/instructions/ap2_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
              return false;
          } else if (arr == '#ap3') {
            $('#formInstructions').click(function(){
                    window.open("../static/instructions/ap3_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
                    return false;
          } else if (arr == '#ap4') {
            $('#formInstructions').click(function(){
                    window.open("../static/instructions/ap4_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
                    return false;
          } else if (arr == '#ap5'){
            $('#formInstructions').click(function(){
              window.open("../static/instructions/ap5_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
              return false;
          }  else {
            return ("Oops! Something seems to be wrong.");
          }
        });
        });

</script>

I am facing issues getting it to work as intended. Is there a way to simplify this?

Answer №1

Obsidian pointed out some errors in the previously mentioned code, so I took the liberty of creating a revised version that should be helpful.

$(document).ready(function(){

    var arr = [ "a1", "a2", "a3", "a4" ];

    $.each( arr, function( i, val ) {

      // Make sure to use the value(val) instead of the array(arr)
      $('#'+val).append('<div id="formInstructions" class="btn btn_'+val+'"><span class="fa fa-question-circle"></span>&nbspForm&nbspInstructions</div>');
      // #a1 ,#b1 ...

       $(window).scroll(function() {              
            var scroll = $(window).scrollTop();
            if (scroll >= 0) {
                $('.btn_'+val).fadeIn();
                //.btn_a1 , btn_b1...
            } else {
                $('.btn_'+val).fadeOut();
                //.btn_a1, btn_b1...
            }
        });

        $('.btn_'+val).click(function(){  
            // Now you can implement the if statement  
            if (val == 'a1') {
                window.open("../static/instructions/ap1_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
            } else if (val == 'a2'){
                window.open("../static/instructions/ap2_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
            } else if (val == 'a3') {
                window.open("../static/instructions/ap3_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");       
            }  else {   
                return ("Oops, something seems to have gone wrong!!");
            }     
            return false;
        });// END CLICK
    }); //END EACH
});

Answer №2

Thank you to Obsidian, Ron, and Jim for your valuable feedback. I have carefully implemented the changes based on your suggestions, and now everything is functioning perfectly. Please see the updated code snippet below!

// Updating and appending instructions
$(document).ready(function() {
  'use strict';

  var arr = ["ap1", "ap2", "ap3", "ap4", "ap5", "ap6", "ap7", "ap8", "ap9", "ap10", "ap11", "ap12", "ap13", "ap14", "ap15", "ap17", "apa", "apb", "apc", "apd", "ape", "apf", "apg", "apj", "aph", "api", "apj", "apk", "apl", "apm", "apn", "apo", "app"];

  $.each(arr, function(i, val) {

    // Using individual values instead of array
    $('#' + val).append('<div id="formInstructions" class="btn btn-aprs"><span class="fa fa-question-circle"></span>&nbspForm&nbspInstructions</div>');

    $(window).scroll(function() {
      var scroll = $(window).scrollTop();
      
      if (scroll !== 0) {
        $('#formInstructions').fadeIn();
      } else {
        $('#formInstructions').fadeOut();
      }
    });

    $('#formInstructions').click(function() {
      if (val === 'ap1') {
        window.open("../static/instructions/ap1_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
      } else if (val === 'ap2') {
        window.open("../static/instructions/ap2_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
      } else if (val === 'ap3') {
        window.open("../static/instructions/ap3_instrns.pdf", "_blank", "toolbar=no,menubar=no,scrollbars=no, statusbar=no,resizable=yes,top=500,left=500,width=600,height=600");
      } else {
        return ("Oops! Something seems to be amiss.");
      }
      return false;
    }); 
  });
}); 
#formInstructions {
  position: fixed;
  bottom: 10px;
  left: 10px;
  cursor: pointer;
  display: none;
}
<div id="ap1"></div>

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

Ways to evenly distribute children in a row using CSS

https://i.stack.imgur.com/HmziN.png The image above showcases the desired effect I am aiming for. It is important to note that the width of the container div may vary. The child elements should have consistent spacing between each other as well as the le ...

"Commander.js does not process query strings when used in conjunction with node

I developed a CLI tool using commander.js which has been released on npm. This command-line interface utilizes node-fetch to fetch data from an external API. However, I have received reports from some users stating that the query string in the fetch URL is ...

What is the best way to utilize MongoDB aggregate in this particular scenario?

How can I optimize this mongoose query to improve performance and reduce size for production? const currentYear = (new Date).getFullYear() const usedCars = await CarModel.find({ ModelYear: {$lte: currentYear - 1} }).limit(10) const recentCars = await Car ...

Filter items by nested properties in ngRepeat

Is it possible to filter a complex object with nested properties using the ng-repeat filter? Can we achieve this filtering with the ng-repeat filter provided out of the box? Data { Name: 'John Smith', Manager: { id: 123, Name: &a ...

Can a custom structural directive be utilized under certain circumstances within Angular?

Presently, I am working with a unique custom structural directive that looks like this: <div *someDirective>. This specific directive displays a div only when certain conditions are met. However, I am faced with the challenge of implementing condit ...

NodeJS sqs-consumer continuously triggers the function to execute

I have been utilizing the npm package called sqs-consumer to monitor messages in a queue. Upon receiving a new message, I aim to generate a subfolder within an S3 bucket. However, I am encountering a problem where even after the message is processed and re ...

Troubleshooting problem: AJAX autocomplete URL returning XML

I found my code reference here: http://example.com/code-reference if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes-> ...

Using a nested table will override the "table-layout: fixed" property

I'm currently working on creating a tabular layout and I'm in need of the following: 2 columns with variable widths Columns that are equal in width Columns that are only as wide as necessary After some research, I discovered that by setting "t ...

Is there a way to continually update a specific portion of a webpage using AJAX without manual intervention?

$messages = $db->query("SELECT * FROM chatmessages ORDER BY datetime DESC, displayorderid DESC LIMIT 0,10"); while($message = $db->fetch_array($messages)) { $oldMessage[] = $message['message']; } $oldMessages = array_reverse($oldMessage ...

How to extract keys from an object using jQuery

I am currently working on implementing a Modal in bootstrap 5. I found a helpful guide at http://jsfiddle.net/341tfz8j/1/. I made the necessary changes to update the references from bootstrap 4 to bootstrap 5, such as changing data-toggle to data-bs-toggle ...

jsp fullcalendar select not functioning properly

The code snippet for the select: function within fullcalendar is as follows: select: function(start, end, jsEvent, view) { if (start.isBefore(moment())) { $('#calendar').fullCalendar('unselect'); return false; } else { //ajax Cal ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

several javascript onclick event listeners for manipulating the DOM

I am currently experimenting with d3 and attempting to create a simple webpage to showcase my d3 examples for future reference. The page displays the output of the d3 code (specifically, the force layout from Mike Bostock) and then embeds the correspondin ...

Building on the functionality of AngularJS, a directive scope can be established to access and modify

Can a directive accept and utilize a parameter as its scope value? For instance: angular .module('app', []) .controller('CTRL', function($scope) { $scope.some_value = { instance1: { key1: 'value11', ...

Implementing personalized font styles in HTML on a WordPress platform

I recently followed a tutorial on how to upload custom fonts to my WordPress website, which you can find at the link below. I completed all the necessary steps, such as uploading to the ftp, modifying the header.php file to include the font stylesheet, and ...

The "Splash Screen Div" page displayed during transitions and page loading

Creating a "Splash Screen Div" for a loading page involves waiting until everything is loaded and then hiding or moving the div off screen. Below is an example: index.html <div id="loading-Div"> <div id="bear-Logo"> < ...

Retrieving Value from Dynamic Content Using jQuery `.keypress()` and `.delegate()`

I have encountered an issue with my code that is unable to retrieve the value of a specific ID on the .keypress function after using .delegate. The ID and other contents are generated dynamically through an AJAX call. $(document).delegate('.edit_ ...

Creating links within a single image in HTML?

Is there a way to hyperlink different parts of a single image to various webpages using JavaScript coordinates or any other method? ...

The advice I received was to avoid using max-width and instead utilize min-width when styling with CSS

With @media screen and (max-width:700px) { Link to image 1 Whenever I use @media screen and (min-width: 700px) { it messes up. How can I adjust it for min-width without causing issues? Link to image 2 ...

Designing a personalized carousel component in Angular

Looking to replicate this design, any tips? I'm aiming for a carousel layout with developers listed in a project, where the center item is larger than the others. Any guidance on how to achieve this look? ...