Mārcis
Mārcis

Reputation: 91

Apply scrollIntoView function in to JQuery function

I am using JQuery show and hide function, it works like when you click on image it opens a information log. The information log opens at the top of the page, so I need to make that when you click on the image on bottom on the page it scroll you up to the content.

JQuery what I am using for my hide and show content:

jQuery(function() {
  jQuery('.showSingle').click(function() {
    jQuery('.targetDiv').hide();
    jQuery('#div' + $(this).attr('target')).show();
  });
});

Scrolintoview function that I tried to use:

function myFunction() {
  var elmnt = document.getElementById("targetDiv");
  elmnt.scrollIntoView();
}

Content from witch I am calling both functions:

<a  onclick="myFunction()" class="showSingle" target="{$ID}">
    //HTML content here
</a>

Content what I am calling to shop up at the top of the page:

<div id="div{$ID}" class="targetDiv SlideDiv">
    //HTML content here 
</div>

I tried to combine this two JS function but only jQuery('.targetDiv').hide() works for me.

Upvotes: 0

Views: 144

Answers (1)

Wendelin
Wendelin

Reputation: 2401

The problem is that your target div

<div id="div{$ID}" class="targetDiv SlideDiv">
//HTML content here 
</div>

has some id and the classes targetDiv and SlideDiv.

document.getElementById("targetDiv") tries to find an element with the id targetDiv but your element does not have this id, but is has a class with the same name.

You need to find the element by its class which can be done in a few ways:

1

var elem = document.getElementsByClassName("targetDiv")[0];

2

var elem = document.querySelector(".targetDiv");

3

var elem = $(".targetDiv")[0];

Upvotes: 1

Related Questions