Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Div Content onclick

Tags:

html

jquery

css

I know nothing about jQuery but want to achieve something really important.

I want to have a button/link that will replace the div content and if I press that button again so it will put the original content back in position.

like image 609
Junaid Khawaja Avatar asked Sep 09 '14 01:09

Junaid Khawaja


People also ask

How do I change content on click?

To change the text of a button on click:Add a click event listener to the button. Use the textContent property to change the button's text. For example, btn. textContent = 'Button clicked' .

How do I replace HTML in a div?

Answer: Use the jQuery html() Method You can simply use the jQuery html() method to replace innerHTML of a div or any other element.


1 Answers

Here's an approach:

HTML:

<div id="1">
    My Content 1
</div>

<div id="2" style="display:none;">
    My Dynamic Content
</div>
<button id="btnClick">Click me!</button>

jQuery:

$('#btnClick').on('click',function(){
    if($('#1').css('display')!='none'){
    $('#2').html('Here is my dynamic content').show().siblings('div').hide();
    }else if($('#2').css('display')!='none'){
        $('#1').show().siblings('div').hide();
    }
});


JsFiddle:
http://jsfiddle.net/ha6qp7w4/
http://jsfiddle.net/ha6qp7w4/4 <--- Commented

like image 86
BernardoLima Avatar answered Oct 05 '22 22:10

BernardoLima