ygtahmet
ygtahmet

Reputation: 1

Pass a variable to other function in javascript

$('.header_menu_item').on('mouseenter',function(){
    var default_img = $(this).find('.header_menu_item_icon_img').attr('src');
    var hover_img = $(this).find('.header_menu_item_icon_img').attr('data-hover');
    $(this).find('.header_menu_item_icon_img').prop('src',hover_img);
}).on('mouseleave',function(){
    $(this).find('.header_menu_item_icon_img').prop('src',default_img);
});

How can i pass default_img var to following mouseleave function? Thanks for any help :)

Upvotes: 0

Views: 76

Answers (4)

Patrick Evans
Patrick Evans

Reputation: 42736

Set it as data on the element itself and then retrieve it later

//setting
$(this).data('default_img',default_img);

//retrieving
var img = $(this).data('default_img'); 

Through native js

//setting
this.dataset['default_img'] = default_img;

//retrieving
var img = this.dataset['default_img'];

You could also before hand set up a data-* attribute on the html itself so no need to use JS to set the initial data

<img src="http://example.com/someimg.jpg" data-default_img="http://example.com/someimg.jpg" />

data-* attributes reference

dataset reference

jQuery's data() method

Upvotes: 1

Thomas Fellinger
Thomas Fellinger

Reputation: 656

you can not pass it directly - you can store it in an outer variable - but you have to do it by each item:

$('.header_menu_item').each(function(){

  var $header_menu_item_icon_img = $(this).find('.header_menu_item_icon_img'),
      default_img = $header_menu_item_icon_img.attr('src'),
      hover_img = $header_menu_item_icon_img.attr('data-hover');

  $(this).on('mouseenter',function(){ 
    $header_menu_item_icon_img.prop('src',hover_img);
  }).on('mouseleave',function(){
    $header_menu_item_icon_img.prop('src',default_img); 
  });
});

Upvotes: -1

Barmar
Barmar

Reputation: 780724

You need to use global variables. A function can only pass variables directly to functions that it calls, not functions that are called outside.

var default_img;
$('.header_menu_item').on('mouseenter',function(){
    default_img = $(this).find('.header_menu_item_icon_img').attr('src');
    var hover_img = $(this).find('.header_menu_item_icon_img').attr('data-hover');
    $(this).find('.header_menu_item_icon_img').prop('src',hover_img);
}).on('mouseleave',function(){
    $(this).find('.header_menu_item_icon_img').prop('src',default_img);
});

Upvotes: 0

Jose Rojas
Jose Rojas

Reputation: 3520

One option will be declare a variable outside of the 2 functions.

var default_img = '';
$('.header_menu_item').on('mouseenter',function(){
default_img = $(this).find('.header_menu_item_icon_img').attr('src');
   var hover_img = $(this).find('.header_menu_item_icon_img').attr('data-hover');
   $(this).find('.header_menu_item_icon_img').prop('src',hover_img);
}).on('mouseleave',function(){
   $(this).find('.header_menu_item_icon_img').prop('src',default_img);
});

Upvotes: 2

Related Questions