Nicole Haines
Nicole Haines

Reputation: 191

jQuery .slideToggle Usage

I am trying to place an anchor tag inside an article element that has the jQuery .slideToggle function attached to it.

This is the html:

<section id="recent_articles">

<article>

<img src="images/image1.jpg">
<h1>Insert title here</h1>
<p>Insert text here followed by an anchor tag<a href=#>Read More</a></p>

</article>

</section>

The jQuery looks like this:

$( "#recent_articles > article" ).click(function(e) {

        $(this).children("p").slideToggle(1000);
        $(this).toggleClass("open");

    });

I understand that the jQuery is "activating" whenever the article element is clicked (including the image element) and the paragraph is sliding down and up as instructed.

This means however that the anchor element is not accessible as it responds to jQuery and not the href attribute.

Using jQuery, how would I access the anchor element so that it responds with default link behavior and not the .slideToggle function.

I am very VERY new at using jQuery so any advice would be appreciated.

Upvotes: 1

Views: 112

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206618

On click you can watch on the event.target Element (the one who called the event) tagName,
if it's not an anchor "A" than do the thing

$( "#recent_articles > article" ).click(function(ev) {
  if(ev.target.tagName!=="A"){
    $(this).children("p").slideToggle(1000);
    $(this).toggleClass("open");
  }
});

otherwise you can do it like you already do just adding another function bound to the a element that will prevent the click event to propagate (bubble up) to the article:

$( "#recent_articles > article" ).click(function(e) {
    $(this).children("p").slideToggle(1000);
    $(this).toggleClass("open");
}).find('a').click(function(e){ // find `a` inside `article` and on click...
   e.stopPropagation();         // don't propagate the event up to `article`
});

P.S: your function can be also a bit shorter like:

$( "#recent_articles > article" ).click(function(e) {
    $(this).toggleClass("open").children("p").slideToggle(1000);
}).find('a').click(function(e){
   e.stopPropagation();
});

Upvotes: 1

Related Questions