bdrelling
bdrelling

Reputation: 850

How Do I Store A PHP Variable In JS For Use With jQuery?

I'm wondering where I would put code to take a variable from PHP (used in numbering classes) and store it in a variable that jQuery can access?

Here is an example:

$(".object1-22").hover(function(e){
    $(".object2-22").show();
}, function(e) {
    $(".object2-22").hide();
});

So in my code, I have two objects. When you hover over the 22nd instance of object1, I want it to only display the 22nd instance of object2.

How could I perform this task?

Upvotes: 0

Views: 71

Answers (2)

Jaime
Jaime

Reputation: 1410

Couldn't you just echo the php variable out in to the javascript? Or am I misunderstanding your question?

jsVar = <?php echo $phpVar; ?>

Upvotes: 0

Tomalak
Tomalak

Reputation: 338416

If you create IDs for your objects ("22nd instance of object2"), use HTML IDs, not CSS classes.

I guess you want the same behavior for all the objects, so do not write separate event handlers for each of them. Use a common CSS class (object1 and object2) and individual IDs (object1-22, object2-22)

Consider

$(".object1").hover(function(e){
    $('#' + this.id.replace(/object1-/, 'object2-').show();
}, function(e) {
    $('#' + this.id.replace(/object1-/, 'object2-').hide();
});

You could even link the related elements beforehand.

$(".object1")
.each(function () {
    this.partner = $(this.id.replace(/^object1-/, 'object2-')[0];
})
.hover(function () {
    $(this.partner).show();
}, function () {
    $(this.partner).hide();
});

That being said, this is a question for StackOverflow, unfortunately I do not have enough rep here to flag it accordingly.

Upvotes: 2

Related Questions