简体   繁体   中英

Having an element on a page clicked on page load

So I'm working with a Squarespace template and I figured that the easiest way to have a certain behavior occur (basically showing a div that normally stays hidden until a banner is clicked) is to fake a click on the banner itself.

I have two issues here:

  1. The particular element cannot be consistently singled out, as the ID seems to change partially every time. So I need to basically get the first element of this class that occurs and the anchor tag within.
  2. With all the nesting, I'm not sure what exactly needs to be clicked. Is it the div, or the anchor tag, or what?

Here's the code:

<div class="item sqs-gallery-design-autocolumns-slide" id="someidthatchanges" data-type="image" style="top: 0px; left: 0px; width: 1440px; height: 514px;" overlaydelay="236">
      <a href="thelink" data-dynamic-load="" data-dynamic-receiver="#somestuff" id="idthatchanges">
        <div class="wrapper" id="idthatchanges">
          <div class="project-title" id="idthatchanges">
            <h2 id="idthatchanges">+</h2>
            <h3>— view —</h3>
          </div>
        </div>
        <img src="someUnimportantImage.gif"/>
     </a>
</div>

Here's my unsuccessful jQuery attempt:

$("document").ready(function() {
  $('#changingDivID').find('a').trigger('click');
});

The above doesn't work in the console either (even when the ID is correct), but doesn't give any errors so it appears to be a targeting issue of some sort.

Any ideas?

Calling .trigger('click') or jQuery's .click() method doesn't actually trigger an anchor's default click behaviour (it just triggers event handlers bound with jQuery and inline click handlers). You can work around that by calling the DOM element's native .click() method instead.

Put that together with your note about targetting the first element with the class:

$("document").ready(function() {
  $('.sqs-gallery-design-autocolumns-slide:first a')[0].click();
});

I'm not sure what exactly needs to be clicked. Is it the div, or the anchor tag, or what?

Well the HTML shown doesn't have any inline event handlers, so we can't tell which element you should target. Except that logically it should be the anchor because that is what keyboard-only users can "click".

maybe what you want is something like this.

$(document).ready(function(){
 $(".item.sqs-gallery-design-autocolumns-slide").find("a").click();
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM