Avatar of Mark Bran
Mark Bran

asked on 

scrollIntoView(); trouble getting it to work

Here is a code pen with my code
https://codepen.io/jsMarko/pen/c115a9b2edc350fe342c9e2b365d6300?editors=1111
Having trouble in my js

Essentially I am using Template Literal to create anchor buttons that when clicked should scroll to the respective section. However, in the test code in above codepen is not working
I just cant seem to see why its not scrolling
Also note the e.preventDefault is not working either as it is still cycling through the sections because of the Anchor href pointing to them

Here is the area I think is the concern const evListen = document.querySelector('#contactLink'); // getting contactLink

const evListen = document.querySelector('#contactLink'); // getting contactLink
evListen.addEventListener('click', (e) => {
   e.preventDefault();
   let contactEv = document.querySelector('#contact');  
   contactEv.scrollIntoView();
   console.log('It clicked'); // It clicked is working
   });
JavaScript

Avatar of undefined
Last Comment
Michel Plungjan
Avatar of Mark Bran
Mark Bran

ASKER

NOTE: I resolved this with this code ... but how might I stream line this

const homeLink = document.getElementById('homeLink');
homeLink.onclick = function(e) {
  e.preventDefault();
  document.querySelector('#home').scrollIntoView({block: 'start', behavior: 'smooth'});
}
const servLink = document.getElementById('servicesLink');
servLink.onclick = function(e) {
  e.preventDefault();
  document.querySelector('#services').scrollIntoView({block: 'start', behavior: 'smooth'});
}
const teamLink = document.getElementById('teamLink');
teamLink.onclick = function(e) {
  e.preventDefault();
  document.querySelector('#team').scrollIntoView({block: 'start', behavior: 'smooth'});
}
const conLink = document.getElementById('contactLink');
conLink.onclick = function(e) {
  e.preventDefault();
  document.querySelector('#contact').scrollIntoView({block: 'start', behavior: 'smooth'});
}

Instead of repeating the functions over and over how
might I write one function that could be called by the anchor onclick events?
ASKER CERTIFIED SOLUTION
Avatar of Jeffrey Dake
Jeffrey Dake
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Jeffrey Dake
Jeffrey Dake
Flag of United States of America image

If you are using jquery I would do something like this
<a id="contactLink" data-link="contact"></a>

$("A[data-link]").on("click" , (function(e) {
   var targetData = $(this).attr("data-link");
   document.querySelector('#' + targetData).scrollIntoView({block: 'start', behavior: 'smooth'}
});

Open in new window

Avatar of Mark Bran
Mark Bran

ASKER

Dont know jquery but that looked interesting

That said adding the onclick to the link is doable
I am creating the links using a Template Literal
let myEl = ['home', 'services', 'team', 'contact'];
// ******* Parse the Array and get all ID names *********
// Use Template Literal to create li then place it in UL
let output = myEl.map((id) => {
  return `
            <li><a href='#${id}' id='${id}Link'>${id}</a></li>
         `;
});

// ******* Used .join('') on output to remove the trailing commas
document.getElementById('mylist').innerHTML = output.join('');


I can adjust the template to include the onclick as you merntioned ... see how that works :) Ill let you know
Avatar of Mark Bran
Mark Bran

ASKER

Ok this not turning out as easy as I thought here is whats happening

let output = myEl.map((id) => {
  return `
            <li><a id='${id}Link' onClick='document.querySelector('#${id}').scrollIntoView({block: 'start', behavior: 'smooth'}); return false;' >${id}</a></li>
         `;
});

The results are
  <a id="homeLink" onclick="document.querySelector(" #home').scrollintoview({block:="" 'start',="" behavior:="" 'smooth'});="" return="" false;'="">home</a>

As you can see its adding      =""  <----- so ofcourse its not working .... never had Template Literal do that before ..... any thoughts what I could do to fix it?
Avatar of Mark Bran
Mark Bran

ASKER

forgot to mention  M getting this error
SyntaxError: expected expression, got '}'

Im not seeing it though
Avatar of Mark Bran
Mark Bran

ASKER

Thank you that was the answer ... I figured out how to create the link with the onClick as you showed it ... works like a charm

I used template literal
let output = myEl.map(({id}) => {
  return `
            <li><a id='${id}Link' onClick="document.querySelector('#${id}').scrollIntoView({block:'start',behavior:'smooth'});return false;" >${id}</a></li>
           
         `;
});
got it done ..... Thanx
Based on the lack of animation in the original question, may I ask why not just
document.getElementById('mylist').innerHTML = myEl.map(id => `<li><a id='${id}Link' href='#${id}'>${id}</a></li>`).join('');

Open in new window

or even without the ID if you do not need it

document.getElementById('mylist').innerHTML = myEl.map(id => `<li><a href='#${id}'>${id}</a></li>`).join('');

Open in new window


JavaScript
JavaScript

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.

127K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo