Home > Software engineering >  Change a global variable from inside an if-function
Change a global variable from inside an if-function

Time:04-01

I have a hotspot image thingy thing where you got spots (called "items") hovering on the image which are clickable. When you click such an item, a textbox appears on the right side of the image with all the information. Now if you click another item, the textbox should close and a new one opens up.

This is the current code:

jQuery(document).ready(function() {
        counter = 1;
        var lastHotspot = 0;
        
        jQuery("#{{item.item_id}}").click(function(){
            if (counter == 1) {
                 jQuery("#textbox{{item.item_id}}").show();
                 lastHotspot = {{item.item_id}};
                 counter  ;
            } else {
                jQuery("#textbox"   lastHotspot).hide();
                jQuery("#textbox{{item.item_id}}").show(); 
                lastHotspot = {{item.item_id}};
           }                                              
        });              
});

Because there isn't a textbox the first time everything loads, I want to run the ".show" on the textbox the first time you click an item and then store the item's ID. After that, when I click an item, it should ".hide" the textbox of the previous item, then ".show" the next textbox from the clicked item and then re-assign the item-ID to "lastHotspot" and then repeat everytime an item gets clicked.

The problem I have is, that "lastHotspot" doesnt get stored inside the variable after getting re-assigned inside the if-function, even tho the counter does. How can I fix this issue?

CodePudding user response:

You can either bind the functions before you attach them to the click events, or you can use a global object to modify the counters:

jQuery(document).ready(function() {
        counter = 1;
        var lastHotspot = 0;
        
        jQuery("#{{item.item_id}}").click((function(){
            if (counter == 1) {
                 jQuery("#textbox{{item.item_id}}").show();
                 lastHotspot = {{item.item_id}};
                 counter  ;
            } else {
                jQuery("#textbox"   lastHotspot).hide();
                jQuery("#textbox{{item.item_id}}").show(); 
                lastHotspot = {{item.item_id}};
           }                                              
        }).bind(this));              
});

Using global Object:

jQuery(document).ready(function() {
        configs = { counter: 1 };
        var lastHotspot = 0;
        
        jQuery("#{{item.item_id}}").click(function(){
            if (configs.counter == 1) {
                 jQuery("#textbox{{item.item_id}}").show();
                 lastHotspot = {{item.item_id}};
                 configs.counter  ;
            } else {
                <...>
           }                                              
        });              
});
  • Related