3

Currently as per Jquery site .toggle() has been depreciated after 1.8 version. So is there any alternative to .toggle() as i need the function for menu app in which I need to hide and show contents of a div based on button click

I have already accomplished the task according to JSFiddle but I am already loading 1.12.4 version of jquery on my site for other usage

my Js function code

function hideToggle(button, elem) {

  $(button).toggle(
    function() {
      $(elem).hide();
    },
    function() {
      $(elem).show();
    }  );
}

hideToggle(".button1", ".iframe1");

So is there a way to prevent loading two versions of jquery

Darsh kotecha
  • 31
  • 1
  • 5
  • 1
    From the page you link to: *"The .toggle() method is provided for convenience. It **is relatively straightforward to implement the same behaviour** by hand"* – freedomn-m Dec 13 '16 at 12:25

5 Answers5

5

This is basically what hide and show are doing.

CSS

.hidden {
 display:none;
 /* you could also use !important here */
}

JQuery

  $('#someElement').toggleClass('hidden');
bassxzero
  • 4,838
  • 22
  • 34
2

They do not seem to have replaced it with an equivalent method. However, you can do this:

$(button).on('click', function() {
    if ($(elem).is(':visible') { // if $(elem) is visible
        $(elem).hide(); / hide it
    } else { // if not
        $(elem).show(); // show it
    }
DevlshOne
  • 8,357
  • 1
  • 29
  • 37
2

Bizarrely, the simple solution to this is a different toggle function. This function toggles the display of the element.

Your function could be simplified to

function hideToggle(button, elem) {
  $(button).click(
    function() {
      $(elem).toggle();
    }
  );
}
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
1

You can call .toggle() on click to achieve exactly the same thing:

$(".button1").click(function() { $(".iframe1").toggle();});
$(".button2").click(function() { $(".iframe2").toggle();});

Updated fiddle: https://jsfiddle.net/6g3cko1h/3/ including an updated version of your utility-style setup method:

function hideToggle(button, elem)
{
    $(button).click(function() { $(elem).toggle(); })
}
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
-1

You are not understanding right what was deprecated. The toggle function is valid. Which is "Display or hide the matched elements".

The current documentation for toggle is - http://api.jquery.com/toggle/

so

$('button').toggle()

Would hide the element if it was visible, or show it - if it was visible

knaos
  • 820
  • 7
  • 13
  • 1
    Sorry, but OP is clearing using `$(button).toggle(function...)` which *is* the deprecated toggle function and is looking for an alternative. The *other* toggle function is not deprecated as you assert here. – freedomn-m Dec 13 '16 at 12:32
  • 1
    I agree. I think @lonesomeday 's answer is the best – knaos Dec 13 '16 at 12:40