Ansver
Ansver

Reputation: 94

Is it possible to bind to JQuery attr to js variable?

Is is possible to bind JQuery attr to js variable like this?

var pathToImg = "assets/images/picture1.png"
$("#background-image").attr("href", pathToImg)

I want that when I change pathToImg depending on state then element #background-image changes dynamically.

Does it work like this under hood? While I don't use it. I want to figure out how I can do this?

Upvotes: 1

Views: 134

Answers (3)

vijayliebe
vijayliebe

Reputation: 168

You can implement watcher on js variable and in watcher method write change behaviour code :-

Object.defineProperty(this, 'pathToImg', { //watcher on js variable
    get: function () { return this._pathToImg; },
    set: function (v) {
        this._pathToImg = v;
        $("#background-image").attr("src", v); //change behaviour code
    }
});

Upvotes: 0

Justinas
Justinas

Reputation: 43451

No, it does not work like that. Use some front-end frameworks like Angular or React that has state (obvious not full/valid code, sample in Angular):

...
var this.$scope.pathToImg = "assets/images/picture1.png";
...

this.$scope.pathToImg = "assets/images/picture2.png";

<div><img src="{{pathToImg}}"/></div>

In jQuery you can use some functions to change it dynamically:

var currentIndex = 1;
var baseUrl = 'http://via.placeholder.com/350x150?text=';

function plus() {
  currentIndex++;
  update();
}

function minus() {
  currentIndex--;
  update();
}

function update() {
  currentIndex = Math.max(1, currentIndex);
  $('#myImg').attr('src', baseUrl+currentIndex);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://via.placeholder.com/350x150?text=1" id="myImg"/>
<hr/>
<button onClick="minus()">-</button>
<button onClick="plus()">+</button>

Upvotes: 0

Gagan Deep
Gagan Deep

Reputation: 1509

As far as i know, No it doesn't work like that. You need to capture an event when the value of the variable changes and set the value of the attribute again.

Upvotes: 2

Related Questions