0

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?

1
  • 1
    See wp_localize_script. Commented Aug 2, 2011 at 15:51

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I apologize for posting it in the wrong spot. I assumed it would be good here since I searched jQuery on SE and this was the first result. I'll repost it elsewhere.
@Aerodynamo never mind re-posting, this question will get migrated if it finds the interest of some high-rep users here. (Besides, maybe it's more related to WP than I realize, I'm only here by accident.)
0

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

jsVar = <?php echo $phpVar; ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.