Mintblaze Mintblaze - 24 days ago 6
Javascript Question

Assigning element's id to variable on .hover() for use in click event

I have 12 elements on my page(however below I have only written code for 3). When one is clicked, the other 11 disappear(using animation called 'spinOut'). Instead of writing code to run on click for each individual element, I want the the id of the element to be assigned to the

$test
variable upon hovering, and then upon
$test
(the element hovered on) being clicked, my code to be carried out for that element. So I will only have to write out one block of code that will be applied to
$test
which means it will be applied to any element that's been clicked on.

I am trying to assign a value to the variable $test inside the .hover() function and then use it outside. I have found many posts where people have had similar problem but none of the solutions that fixed their problems have helped me. I want to know how can I assign the
$test
variable inside the .hover() function and then use it outside.

$(document).ready(function () {
var $test;

$("#M").hover(function () {
$test = "#M";
});
$("#N").hover(function () {
$test = "#N";
});
$("#O").hover(function () {
$test = "#O";
});

//When I define variable value here it works
$($test).click(function () {
$(".pageItem:not("+$test+")").addClass("spinOut");
});
});

Answer

Here's how I got it to work. The 12 elements on my page where all part of ".pageItem" class. I don't have to specify the specific element in $().click - I just have to run code upon any .pageItem being clicked, then use the $test variable inside the function to target the .pageItem that had been clicked on. The code will be applied to the element I last hovered on - impossible to click one of the elements without hovering on them first.

$("#M").hover(function () {
    $test = "#M";
});
$("#N").hover(function () {
    $test = "#N";
});
$("#O").hover(function () {
    $test = "#O";
});
$(.pageItem).click(function () {
    $(".pageItem:not("+$test+")").addClass("spinOut");
});

However, there is a much simpler and more logical way of doing what I needed. Instead of filling $test with the id of the .pageItem I last hovered on and using it to specify what I had clicked on, I assign $(this).attr("id") to $test inside the .click() function like so:

$(.pageItem).click(function () {
    $test = $(this).attr("id");
    $(".pageItem:not("+$test+")").addClass("spinOut");
});