Smooth scrolling using javascript on anchor link - javascript

I want to make smooth scrolling using javascript in php program
As shown in image if i clicked on the customer from my left side bar then i want to smooth scrolling using javascript onclick function what i do?here i pass dynamic id whic are i fetched from my database
<div class="col-md-3 col-sm-12" >
<ul data-spy="affix" data-offset-top="205" class="myclasss">
<?php
foreach($var as $name) { ?>
<a id="#<?php echo $name['name'];?>" class="list-group-item" onclick="scrollFaq(this.id);"><?php echo $name['name'];?> </a><?php } ?>
</ul>
</div>
<div class="col-md-9 col-sm-12 ">
<?php $v1 = '';
foreach($var as $data){
?>
<div class="faqHeader" id="<?php echo $data['name'];?>"> <?php echo $data['name'];?> </div>
<div class="panel-group" ">
<?php
foreach($data['data'] as $dat){ ?>
<div class="panel panel-default">
<div class="panel-heading ">
<h4 class="panel-title">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#col<?php
echo $v1;?>" ><?php echo $dat['questions'];?> </a>
</h4>
</div>
<div id="col<?php echo $v1;?>" class="panel-collapse collapse ">
<div class="panel-body">
<?php echo $dat['answer'];?>
</div>
</div>
</div>
<script>
function scrollFaq(str){
alert(str);
}
</script>

Try This :
function scrollFaq(str){
$('html,body').animate({scrollTop:$("#"+str).offset().top}, 500);
}
Make sure you give this Id to your div in for loop like this
<div class="col-md-9 col-sm-12 ">
<?php $v1 = '';
foreach($var as $data){
?>
<div class="faqHeader" id="<?php echo $data['name']; ?>">
<?php echo $data['name'];?>
</div>
<?php } ?>
</div>

A simple example of how you could achieve the smooth scrolling to an element without using jQuery.
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Smooth scroll to element without jQuery</title>
<script>
function scrollFaq( event ){
event.preventDefault();
/*
Current position and target position
Note: I used `dataset.name` rather than
adding the desired ID as an argument to this
function ~ see html below
*/
var cp=event.target.offsetTop;
var fp=document.getElementById( event.target.dataset.name ).offsetTop;
/*
increase step for larger jump per time period
increase time for longer animation
*/
var step=100;
var time=10;
/* initial step */
var pos = cp + step;
/* self-executing anonymous function */
(function(){
var t;
/* increment the position */
pos+=step;
/* clear the timer if we are at the correct location */
if( pos >= fp ){
clearTimeout( t );
return false;
}
/* do the actual scroll */
window.scrollTo( 0, pos );
/* re-run the function until we reach the correct location */
t=setTimeout( arguments.callee, time );
})();
}
</script>
<style>
.large{
margin:0 0 100rem 0;
border:1px solid black;
display:block;
height:100rem;
font-size:1.5rem;
}
a{
display:block;
clear:none;
margin:0 1rem 1rem 1rem;
width:200px;
padding:1rem;
font-size:1rem;
background:blue;
color:white;
border:1px solid black;
}
</style>
</head>
<body>
<?php
$names=array(/* some random names */
'marilyn','jane','rita','sue','bob','customer','worker'
);
foreach( $names as $name ){/* Note the use of the dataset attribute!!! */
echo "$name";
}
foreach( $names as $name ){
echo "<div id='$name' class='large'>$name</div>";
}
?>
</body>
</html>
Or, a better approach that doesn't involve inline event handlers and now uses your original classNames.
The Javascript function does not need to be declared inside whatever loop you have - indeed to do so would be incorrect. Declare the functions at the top of the page and invoke accordingly as shown here. You could copy either example, save and run to see the scroll effect -then it is trivial to adapt to your "use-case"
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Smooth scroll to element without jQuery</title>
<script>
function scrollFaq( event ){
event.preventDefault();
/*
Current position and target position
Note: I used `dataset.name` rather than
adding the desired ID as an argument to this
function ~ see html below
*/
var cp=event.target.offsetTop;
var fp=document.getElementById( event.target.dataset.name ).offsetTop;
/*
increase step for larger jump per time period
increase time for longer animation
*/
var step=50;
var time=10;
/* initial step */
var pos = cp + step;
var t;
(function(){
/* increment the position */
pos+=step;
/* clear the timer if we are at the correct location */
if( pos >= fp ){
clearTimeout( t );
return false;
}
/* do the actual scroll */
window.scrollTo( 0, pos );
/* re-run the function until we reach the correct location */
t=setTimeout( arguments.callee, time );
})();
}
function bindEvents(event){
/*
Get a nodelist containing all the anchors of class "list-group-item"
*/
var col=document.querySelectorAll('a.list-group-item');
/*
Some browsers do not support using the forEach operator on a nodelist
so convert the nodelist ( which is array like ) into a true array
so that "forEach" can be used.
*/
Array.prototype.slice.call( col ).forEach(function(e,i,a){
/*
here
----
"e" refers to the actual DOM node "a"
"i" refers to the "index" within the array
"a" is the array itself
Assign an "onclick" event listener making sure that
the "passive" flag is set to FALSE in this instance
otherwise you will get an error
"Unable to preventDefault inside passive event listener invocation."
*/
e.addEventListener( 'click', scrollFaq, { passive:false, capture:false });
});
}
/*
Bind the events when the DOM is ready - here we can set the "passive" flag to true
*/
document.addEventListener( 'DOMContentLoaded', bindEvents, { capture:false, passive:true } );
</script>
<style>
.faqHeader{
margin:0 0 100rem 0;
border:1px solid black;
display:block;
height:100rem;
font-size:1.5rem;
}
a.list-group-item{
display:block;
clear:none;
margin:0 1rem 1rem 1rem;
width:200px;
padding:1rem;
font-size:1rem;
background:blue;
color:white;
border:1px solid black;
}
</style>
</head>
<body>
<a name='top'></a>
<?php
$names=array(/* some random names */
'marilyn','jane','rita','sue','bob','customer','worker'
);
foreach( $names as $name ){/* Note the use of the dataset attribute!!! */
echo "<a class='list-group-item' href='#' data-name='$name'>$name</a>";
}
foreach( $names as $name ){
echo "
<div class='faqHeader' id='$name'>
<a href='#top'>$name</a>
</div>";
}
?>
</body>
</html>

Related

How to change on click action to go to link instead of inputting text

So, I am using the AJAX Live Search PDO
I changed the backend-search to link the displayed words. The problem is if you click on the table that it doesn't take them to the link, but just inputs the text. I want to be able to link the entire row... so if they do not just click on the searched word.
I read over the document very thoroughly and did not find the answer.
I think it either is on the JavaScript on line 62 of search-form.php, or one the backend-search.php
I added
<a href=\"" . $row["link"] . "\"> to the backend-search file.
search-form.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Live MySQL Database Search</title>
<style type="text/css">
body{
font-family: Arail, sans-serif;
}
/* Formatting search box */
.search-box{
width: 300px;
position: relative;
display: inline-block;
font-size: 14px;
}
.search-box input[type="text"]{
height: 32px;
padding: 5px 10px;
border: 1px solid #CCCCCC;
font-size: 14px;
}
.result{
position: absolute;
z-index: 999;
top: 100%;
left: 0;
}
.search-box input[type="text"], .result{
width: 100%;
box-sizing: border-box;
}
/* Formatting result items */
.result p{
margin: 0;
padding: 7px 10px;
border: 1px solid #CCCCCC;
border-top: none;
cursor: pointer;
}
.result p:hover{
background: #f2f2f2;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</body>
</html>
backend-search.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
// Attempt search query execution
try{
if(isset($_REQUEST["term"])){
// create prepared statement
$sql = "SELECT * FROM countries WHERE name LIKE :term";
$stmt = $pdo->prepare($sql);
$term = $_REQUEST["term"] . '%';
// bind parameters to statement
$stmt->bindParam(":term", $term);
// execute the prepared statement
$stmt->execute();
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "<p>" . $row["name"] . "</p>";
}
} else{
echo "<p>No matches found</p>";
}
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
?>
I would like when a person clicks anywhere on the row of the results that it goes to the link. Currently they have to click on the hyperlink
you can do that by making the 'a' tag fullwidth(display:block) or cover the 'p' tag with 'a', that will make the whole row clickable.
Here it's a rough example of what you should do. Run the snippet below to check the results (the second link google is not working, it's due to stackoverflow, but if you use on your side, it will work)
$(document).on("click", ".result p", (event) => {
var url =$(event.target).find("a").prop("href"); // getting the clicked element with event target.
window.location = url;
})
p {
width: 100%;
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="result">
<p> stack</p>
<p> google</p>
</div>
I bind the event on the document for various reason. Yours links will be create with a script after the html (DOM) was loaded. Using document permit to bind the event "click" on all ".result p" element even if you add it in the dom after the loading of the page.
$(".result p").click(() => {
var url =$(this).find("a").prop("href");
window.location = url;
});
It will target the same element. But it will bind only to ".result p" element that already exist on your html. Note : with this way the clicked element is "this" and not "event.target", because in the previous event, "this" refers to "document".

Javascript to have a fixed navbar is not working

http://www.new.techmoney360.com/ is the website and it's being developed with wordpress.
That navigarion bar is part of the <header> that also encompass my logo section up top so I'm not sure if that causing issues.
This is the entire html the encompasses the navigation bar that I want to stick to the top when I scroll past it.
<div id="navmenu" class="mkd-menu-area">
<div class="mkd-grid">
<div class="mkd-vertical-align-containers">
<div class="mkd-position-left">
<div class="mkd-position-left-inner">
<?php if(is_active_sidebar('mkd-left-from-main-menu')) : ?>
<?php dynamic_sidebar('mkd-left-from-main-menu'); ?>
<?php endif; ?>
<?php discussion_get_main_menu(); ?>
</div>
</div>
<div class="mkd-position-right">
<div class="mkd-position-right-inner">
<?php if(is_active_sidebar('mkd-right-from-main-menu')) : ?>
<?php dynamic_sidebar('mkd-right-from-main-menu'); ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
This is the javascript I'm using to target the navigation bar (thanks to akinuri for the script)
window.onscroll = changePos;
function changePos() {
var header = document.getElementById("navmenu");
if (window.pageYOffset > 182) {
header.style.position = "absolute";
header.style.top = pageYOffset + "px";
} else {
header.style.position = "";
header.style.top = "";
}
}
Place .mkd-top-bar outside of all wrappers and whatnot, place it below the <body> and in it's css apply position: fixed;
.mkd-top-bar {
background-color: #303030;
position: fixed;
}
Is this what you're looking for?
#Jacob is partially correct, you don't need (as much) JavaScript here. Here's how you can resolve the issue. Replace the current functionality with this:
window.onscroll = stickyNav;
function stickyNav() {
var header = document.getElementById("navmenu");
if (window.pageYOffset > 70) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
Then, create a new class called .sticky with the following styling adjustments:
.sticky {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
Edit: update stickNav to stickyNav.

modify jquery slideshow code to autoplay

I found some code in an article on daniweb.com for a jquery slideshow and got it working pulling data from mysql. I want to modify it so the slide changes automatically every 5 seconds or so, instead of having to click the buttons but don't know how to modify this code to do that...
Here's the current code: It uses a mysql database and php to pull used car info from a table and then display in a slideshow. The idea is to run this on a rasPi with a 7-10" display at our cashier counter or waiting room for customers to see...
Any help would be greatly appreciated, thank you!
$(document).ready(function(){
var currentPosition = 0;
var slideWidth = 950;
var slides = $('.slide');
var numberOfSlides = slides.length;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner div
slides
.wrapAll('<div id="slideInner"></div>')
// Float left to display horizontally, readjust .slides width
.css({
'float' : 'left',
'width' : slideWidth
});
// Set #slideInner width equal to total width of all slides
$('#slideInner').css('width', slideWidth * numberOfSlides);
// Insert controls in the DOM
$('#slideshow')
.prepend('<span class="control" id="leftControl">Clicking moves left</span>')
.append('<span class="control" id="rightControl">Clicking moves right</span>');
// Hide left arrow control on first load
manageControls(currentPosition);
// Create event listeners for .controls clicks
$('.control')
.bind('click', function(){
// Determine new position
currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
// Hide / show controls
manageControls(currentPosition);
// Move slideInner using margin-left
$('#slideInner').animate({
'marginLeft' : slideWidth*(-currentPosition)
});
});
// manageControls: Hides and Shows controls depending on currentPosition
function manageControls(position){
// Hide left arrow if position is first slide
if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
// Hide right arrow if position is last slide
if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
}
});
* {
font-family:Arial;
}
body {
width:800px;
height:572px;
background:linear-gradient(#117dc8,#15527c);
}
.header {
color:white;
font-size:28px;
margin-left:20px;
margin-top:10px;
}
.logo {
position:absolute;
margin-left:720px;
margin-top:-30px;
z-index:10;
width:250px;
}
.container {
position:relative;
background-color:#fafafa;
width:940px;
height:480px;
border-radius:10px;
margin-top:10px;
margin-left:6px;
padding:5px;
z-index:6;
}
#carDisplay {
width:915px;
height:455px;
padding:10px;
border:none;
}
.contact {
position:absolute;
color:white;
margin:15px 80px;
font-size:20px;
}
* {
font-family:Arial;
}
#cert {
color:#e3001b;
}
.cartitle {
font-size:30px;
margin-left:10px;
}
.stock {
font-size:14px;
font-size:18px;
color:#999;
margin-left:10px;
}
.carimg {
width:480px;
padding:5px;
margin-left:10px;
box-shadow:0px 2px 5px 1px #bbb;
}
.details {
padding:30px;
font-size:25px;
}
.price {
font-size:35px;
font-weight:bold;
color:#333;
text-align:center;
margin-top:-20px;
margin-bottom:10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Used Car New Arrivals</title>
<link rel="stylesheet" href="css/mainstyle.css">
<link rel="stylesheet" href="css/framestyle.css">
<script src="jscript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<div class="header"><i>Used Car New Arrivals | </i><span style="font-size:20px;">Falmouth Toyota</span></div>
<img class="logo" src="ft-logo.png" />
<div class="container">
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "usedcars";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM usedcars";
$result = mysqli_query($conn, $sql);
$num = mysql_num_rows($result);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div id='slideshow'>
<div id='slidesContainer'>
<div class='slide'>
<table class='tableStyle'>
<tr>
<td colspan='2'><div class='stock'>Stock: " . $row["stock"] ."</div></td>
</tr>
<tr>
<td colspan='2'><div class='cartitle'><b><span id='cert'>" . $row["certified"] . "</span> " . $row["preowned"]. " " . $row["year"] . " " . $row["make"] . " " . $row["model"] . " " . "</b><span style='font-size:18px;color:#999;'> - " . number_format($row["mileage"]) . " miles</span></div></td>
</tr>
<tr>
<td colspan='2'><hr /></td>
</tr>
<tr>
<td><img class='carimg' src='" .$row["img"] . "' /></td>
<td class='details'><div class='price'>Price: $" . number_format($row["price"]) ."</div><br>
<hr style='margin-top:-25px;'/>
<b>Vehicle Features</b>
<ul>
<li>" . $row["feat1"] . "</li>
<li>" . $row["feat2"] . "</li>
<li>" . $row["feat3"] . "</li>
<li>" . $row["feat4"] . "</li>
</ul>
</td>
<tr>
</table>
</div>
</div>
</div>";
}
}
else {
echo "<span>No images available</span>";
}
mysqli_close($conn);
?>
</div>
<div class="contact">VISIT OUR SHOWROOM FOR MORE INFORMATION ON ANY OF THESE VEHICLES</div>
</body>
<script src="jscript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</html>
Try adding the following code inside a script tag. Feel free to change the slide change duration as per your requirement.
Here 5000 means 5*1000 milli seconds, which is 5 seconds.
window.setInterval(function() {
$('#rightControl.control').click();
}, 5000);
Accept this answer if it helps.
Update: Playing the slideshow continuously (looping)
Note: Replace the existing animate function with the below snippet
$('#slideInner').animate({
'marginLeft' : slideWidth*(-currentPosition)
}, function() {
// if last slide then move the pointer to 1st slide
if(currentPosition == numberOfSlides-1) {
currentPosition = -1;
}
});

image overlay for php generated items

So I have a roll over effect for my mock store, the images and info for each boxes are taking from .sql file and auto generated sections. I want it too cover each section. I could hard code it, but that's a little too draconian.
<div id="scoll" class="group">
<div class="container">
<div class="center_items">
<?php
//external pages area
include_once('config\database.php');
include_once('object/chair.php');
$database = new Database();
$conn = $database->getConnection();
$chair = new Chair($conn);
$stmt = $chair->readAll();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
<div class="product_box" >
<img src="img/<?php echo $row['THUMB']; ?>" alt="chair_image"> </a>
<h4> <?php echo $row['chair_name'];?> </h4>
<p>$<?php echo $row['PRICE'];?></p>
<div class="buy-box-shadow group">
Buy me!
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
JS
onload=init;
function init() {
document.getElementsByClassName("product_box")[0].onmouseover = function(e){
e.preventDefault();
mouseOver();
}
document.getElementsByClassName("product_box")[0].onmouseout = function(e){
e.preventDefault();
mouseOut();
}
function mouseOver() {
document.getElementsByClassName("buy-box-shadow")[0].style.opacity = .9;
}
function mouseOut() {
document.getElementsByClassName("buy-box-shadow")[0].style.opacity = 0;
}
See the code is hard coded to be the first element, a tad confused on how to make it go for every element.
You don't need JavaScript for that, you can do it just with CSS.
.product_box .buy-box-shadow {
opacity: 0.9;
display: none;
}
.product_box:hover .buy-box-shadow {
display: block;
}
Should be able to do this with forEach. Like so:
function init() {
var product_boxes = document.getElementsByClassName("product_box");
product_boxes.forEach(function(currentValue, index, array){
currentValue.onmouseover = function(e){
e.preventDefault();
mouseOver();
}
});

unable to dynamically set height of div

I want to dynamically resize one of my divs to take the height of the viewport using the following javascript
<script>
var applyMapContainerHeight = function() {
var wH = window.screen.height;
wH = parseInt(wH) + 'px';
$("#main-container-col2-rt-layout").css('height',wH);
console.log(wH);
};
$(document).ready(function() {
applyMapContainerHeight();
});
</script>
My div is coded as:
<div class="wrapper">
<?php echo $this->getChildHtml('global_notices') ?>
<div class="page">
<?php echo $this->getChildHtml('header') ?>
<div id="main-container-col2-rt-layout" class="main-container col2- right-layout">
<div class="main">
<?php echo $this->getChildHtml('breadcrumbs') ?>
...........
This is a magento page for my e-commerce site. Please help!
Aside from vm and vh <length> datatypes, I see that your code works!
<style>
body {
margin: 0; padding: 0;
}
.main-container {
background: red;
}
</style>
<body>
<div class="wrapper">
<?php echo $this->getChildHtml('global_notices') ?>
<div class="page">
<?php echo $this->getChildHtml('header') ?>
<div id="main-container-col2-rt-layout" class="main-container col2- right-layout">
<div class="main">
<?php echo $this->getChildHtml('breadcrumbs') ?>
</div>
</div>
</div>
</div>
<script>
var applyMapContainerHeight = function() {
var wH = window.screen.height;
wH = parseInt(wH) + 'px';
document.getElementById("main-container-col2-rt-layout").style.height = wH;
console.log(wH);
};
(function() {
applyMapContainerHeight();
})();
</script>
</body>
Your question was somehow unclear about what the problem really was, but if the problem is you want wrapper and page not to have a white background, then the solution is to apply dynamic width to the highest div element (i mean the grandpa i.e. wrapper).
Css has units specifically for this:
vh and vw
Demo: http://jsfiddle.net/jfbrdomb/show
div.red {
height: 100vh;
width: 100vw;
background-color: red;
}

Categories