View Div with specific content by clicking link

Asked

Viewed 1,289 times

0

Good morning guys, I’m creating this topic because I performed a forum search and found this solution here.

How to open a <div> by clicking on a <a link>?

But I need a more specific solution.

I am developing a quiz, for each question, I created a HELP tag This tag should display a div when clicked (until then, it’s all right)

Problem:

For each HELP tag I need to display specific content. That is, if the link is clicked on question one, the next div should be opened but with the specific content to help in question 1, if the link is clicked on question two, the content to be displayed should refer to question two.. and so on.

My solution:

I can create N Divs with an ID selector with the specific content for each tag . But I would like to simplify this process, something like: use a class to identify the div and compare which Link was clicked to display the specific element within that div, then I would use the same div always, only with the distinct content...

I think that’s it guys, I don’t know if it’s too clear.

Thank you for your attention

  • 2

    How is your code?

  • Post what you already have.

2 answers

2

I don’t really know if this is what I wanted, but from what I understand I made this code to explain to you.

HTML

<button id="tag1">TAG1</button>
<button id="tag2">TAG2</button>

<div id="tagContent"></div>

CSS

div{

display:none;

}

jQuery

$('button').on("click", function() {
        switch($(this).attr('id')) {
    case 'tag1':
        var conteudo = 'conteudo 1';
        break;
    case 'tag2':
        var conteudo = 'conteudo 2';
        break;
        }
    $('div').text(conteudo);
    $('div').slideToggle();
});

1

My approach uses a hidden element within the link itself, which when clicked copies its html content to the presentation div.

I believe that this way it is easier to edit the contents, especially if there are many links, and with dynamic contents coming from the database.

I recommend that all content is always entirely in html, and the script only does the necessary manipulation.

$('a.link').click(function(event) {
  event.preventDefault();
  $('div.content').html($('div', this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="link">Link 1<div style="display:none">Conteudo do link 1</div></a>
<a href="#" class="link">Link 2<div style="display:none">Conteudo do link 2</div></a>
<a href="#" class="link">Link 3<div style="display:none">Conteudo do link 3</div></a>
<div class="content"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.