user2828442
user2828442

Reputation: 2515

JS variable not working inside Ionic

I am trying to manipulate a div using simple JavaScript function. But it is giving error on the variable used:

originalText is not defined

home.ts code:

declare var orginalText: any;

imports ...

export class HomePage{
constructor(){...}

ngOnInit () {

      $('#changeText').click(function(){
         orginalText = $('#content').html();
        $('#content').text("This is text changed using jquery");
      });

      $('#changeText2').click(function(){
        $('#content').html(orginalText);
    });

home.html code:

<a href="#" id="changeText">Click here to change text of div</a>
<a href="#" id="changeText2">Original Div content</a>
<div id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>

When I click on link, it says originalText not defined.

Upvotes: 0

Views: 242

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58533

Just change normal function to arrow function , and access orginalText with this.orginalText ,

orginalText;

ngOnInit () {
    $('#changeText').click(() => {
        this.orginalText = $('#content').html();
        $('#content').text("This is text changed using jquery");
    });

    $('#changeText2').click(() => {
        $('#content').html(this.orginalText);
    });
}

Upvotes: 1

Related Questions