0

I am trying to display different popups based on randomly generated ids. The code I am using is as follows (this is done using Toolset Types in WordPress):

    <div class="id-select" id="[random_number]">
    <div class="service-container">
        <div class="service-image">
            [types field="picture"][/types]
        </div>
        <div class="service-text">
            <p><strong>Item:</strong> [wpv-post-title output="sanitize"]</p>
            <p><strong>Suitable For:</strong> [wpv-post-taxonomy type="memorial-category" format="name"]</p>
            <p><strong>Price:</strong> [types field="price"][/types]</p>
        </div>
    </div>
</div>
<!-- The Modal -->
<div id="myModal-custom" class="modal-custom">

    <!-- Modal content -->
    <div class="modal-content-custom">
        <span class="close-custom">×</span>
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6">
                  <div class="service-image">
                    [types field="picture"][/types]
                  </div>
                </div>
                <div class="col-md-6">
                    <div class="service-text">
                        <p><strong>Item:</strong> [wpv-post-title output="sanitize"]</p>
                        <p><strong>Suitable For:</strong> [wpv-post-taxonomy type="memorial-category" format="name"]</p>
                        <p><strong>Price:</strong> [types field="price"][/types]</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

The JavaScript is as follows:

// Get the modal
var modal = document.getElementById('myModal-custom');
// Get the button that opens the modal
      var ids = [];
      $('.id-select').each(function(i, el) {
        if (el.id == '') {
          return;
        }
        ids.push('#' + el.id);
      });
      //console.log(ids.join(','));

      $(ids.join(',')).on('click', function(e) {
        modal.style.display = "block";
      })
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close-custom")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

The problem im having is that any item i click on the front-end displays the same modal box. Is there anyway I can get it to pick up the correct modal box for a specific item?

The live site - http://79.170.40.172/tc-pinkfin.co.uk/memorials/cemetery/

CalGregoryy
  • 13
  • 1
  • 6
  • you can do using jquery attributes get values to the attributes and change the values dynamically in popup based on click – charan kumar Sep 20 '18 at 11:31

1 Answers1

1

How would you expect modal to be different, when you dont parametrize it in getter anyhow?

var modal = document.getElementById('myModal-custom');

You always ask for same modal, so it s always the same.

Do you have more modals on your page?

Do you somehow pass different data to that one modal and it s not displaying?

On your page I see you display boxes with images and some additional data. Guess you have those images + data in some array like:

const items = [
   { imgSrc: "...", additionalData:{...} },
   { imgSrc: "...", additionalData:{...} },
   { imgSrc: "...", additionalData:{...} },
];

Generally what you need do to is to associate modal with each item (from above array)

Best moment to do that would be at the time when you create those boxes you already have on your page and want to click to show modal (you do that in a loop, right?).

Possible solutions:

  • when creating each box, you can attach click handler to it, pointing to particular modal instance.
  • extend each item object with unique ID and somehow add that ID to proper modal DOM element for each item. Ex. data-modaluid="$uniqueIDFromItem" Than on click on each item, bind click method with that ID (which can also be set as data-itemuid=$uniqueIDFromItem or just binded in click handler) and by that ID search for proper modal DOM node.

There are few ways to do that depending on how you structurized your page and how you handle your data.

HTML

<button>toggle modal 1</button>
<button>toggle modal 2</button>
<button>toggle modal 3</button>

<div class="modal">
  modal 1
</div>
<div class="modal">
  modal 2
</div>
<div class="modal">
  modal 3
</div>

Javascript

General idea is to connect each clickable item with model by unique id (uid).

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

document.addEventListener("DOMContentLoaded", () => {
  const modals = document.querySelectorAll(".modal")
  const buttons = document.querySelectorAll("button")

  let guids = []

  //create unique IDs for modals/buttons
  buttons.forEach(button => {
    guids.push(guid())
  })

  //set those IDs for buttons/modals with same order in array. Creating connections  1->1 2->2 3->3
  guids.forEach((guid, index) => {
    buttons[index].dataset.guid = guid
    modals[index].dataset.guid = guid
  })

  //add onClick event listener for each button
  buttons.forEach(button => {
    button.addEventListener("click", (e) => {
       //find proper div modal with same ID as clicked button
       const divModal = document.querySelector(`div[data-guid="${e.target.dataset.guid}"]`)
       //change its style when not visible assign "visible", otherwise assign "hidden"
       divModal.style.visibility = divModal.style.visibility !== "visible" ? "visible" : "hidden";
    })
  })
})

Codepen:

https://codepen.io/anon/pen/GXzOJv?editors=1011

Credits

GUID method from here: Create GUID / UUID in JavaScript?

azrahel
  • 1,143
  • 2
  • 13
  • 31
  • There's a modal for each product on the site and I totally understand what you mean, is there a way for me to give a random id to each of the modals and associate each item with the specific modals? – CalGregoryy Sep 20 '18 at 11:33
  • @CalGregoryy check now – azrahel Sep 20 '18 at 11:47
  • Yeah, the modals are generated in a loop with their own data. Its just trying to figure out the javascript to select the correct modals. I'm really new to JavaScript, so the two solutions you suggest went straight over my head. – CalGregoryy Sep 20 '18 at 12:51
  • I can associate the same id with the modal and the item, but I'm not sure if you can select the modal based on both the item and modal having the same id. – CalGregoryy Sep 20 '18 at 12:56
  • sure you can :) check my answer now. Best! – azrahel Sep 20 '18 at 13:51
  • @CalGregoryy if that answers your question, can you mark my answer as "answer": )? thanks! – azrahel Sep 21 '18 at 09:05
  • Sorry for the late reply, I was trying to figure out how to implement what you suggested, I have unfortunately had no luck :( – CalGregoryy Sep 24 '18 at 12:10
  • place your code (or something that should work like it) in codepen and make it work like you have it. Post link here, I will help you, so you can check it working. Best – azrahel Sep 24 '18 at 12:26
  • Unfortunately, im using a plugin on wordpress to generate the modals, if you check my temp link - http://79.170.40.172/tc-pinkfin.co.uk/memorials/cemetery/ You will be able to see it on this page :) – CalGregoryy Sep 24 '18 at 14:06
  • I ve checked your link and it works just fine. I see you were able to make it work :) If my answer helped you understand how to achieve that please mark it as an answer @CalGregoryy – azrahel Sep 28 '18 at 15:12