This question already has answers here:
JS & jQuery can't detect html elements, and say's they are undefined
(4 answers)
Closed 7 years ago.
I am writing a HTML code in which there is a form with different radio buttons and the form will automatically be submitted on a click of any radio button and the form data will be submitted to a php file for database querying and the resulting data from the php file will be displayed in an empty div declared below. The problem is, javascript is not executing at all. When i dubmit the form via redirection i.e writing method and action, it is working fine. But as soon as javascript is used, it doesnt work. Moreover, if i write a simple javascript script, that is working. But this script is not.
<!DOCTYPE html>
<?php
include_once 'connection-script.php';
session_start();
if(!isset($_SESSION['email']))
{
header('Location: index.php');
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Competitions</title>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script>
$("#queryform").submit(function(event) {
event.preventDefault();
alert("In the query");
var posting = $.post("previous-grades-student-script.php", $("#queryform").serialize());
posting.done(function(data) {
alert("In the success function");
var content = $(data).find('#showprevioussubmissions');
$("#showprevioussubmissions").html(data);
});
});
</script>
</head>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href='//www.google.com/fonts#UsePlace:use/Collection:Bree+Serif' rel='stylesheet' type='text/css'>
</head>
<body style="background-color:whitesmoke;">
<div id="header" class="header" style="background-color:#6ccecb;">
<?php
$mail=$_SESSION['email'];
$query="SELECT * from student where semail='$mail'";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$filename=$row['studentid']."_dp";
?>
<ul><p>NAME</p>
<?php
if(file_exists('pictures/'.$filename.'.jpg'))
{
echo '<li style="margin:-3% 1% 1% 0%;"><img src="pictures/'.$filename.'.jpg" ><p class="usrname">'.$row['fname'].'</p>';
}
else if(file_exists('pictures/'.$filename.'.gif'))
{
echo '<li style="margin:-3% 1% 1% 0%;"><img src="pictures/'.$filename.'.gif" ><p class="usrname">'.$row['fname'].'</p>';
}
else if(file_exists('pictures/'.$filename.'.png'))
{
echo '<li style="margin:-3% 1% 1% 0%;"><img src="pictures/'.$filename.'.png" ><p class="usrname">'.$row['fname'].'</p>';
}
else
{
echo '<li style="margin:-3% 1% 1% 0%;"><img src="icons/user.png"><p class="usrname">'.$row['fname'].'</p>';
}
?>
<ul>
<li>My Profile</li>
<li>My submissions</li>
</ul>
</li>
<li style=" margin:-3% 1% 1% 0%;">Log Out</li>
</ul>
</div>
<div id="compete" class="compete" style="position:relative; top:5%;">
<div id="table-wrapper" class="table-wrapper">
<h2> Selct a course </h2>
<?php
echo '<form id="queryform" name="queryform" action="/" method="post">';
$result1=mysql_query("SELECT * from `student-course` WHERE studentid='$row[studentid]'");
while($row1=mysql_fetch_assoc($result1))
{
$sql="SELECT * from courses where courseid='$row1[courseid]'";
$answer=mysql_query($sql);
$row2=mysql_fetch_assoc($answer);
echo '<input type="radio" name="courses" value="'.$row2['courseid'].'" onchange="this.form.submit()">'.$row2['coursename'];
}
?>
</form>
</div>
</div>
<div id="showprevioussubmissions">
</div>
</body>
</html>
The above is my file. Plz Help.
EDIT
<!DOCTYPE html>
<?php
include_once 'connection-script.php';
session_start();
if(!isset($_SESSION['email']))
{
header('Location: index.php');
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Competitions</title>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
</head>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href='//www.google.com/fonts#UsePlace:use/Collection:Bree+Serif' rel='stylesheet' type='text/css'>
</head>
<body style="background-color:whitesmoke;">
<div id="header" class="header" style="background-color:#6ccecb;">
<?php
$mail=$_SESSION['email'];
$query="SELECT * from student where semail='$mail'";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$filename=$row['studentid']."_dp";
?>
<ul><p>NAME</p>
<?php
if(file_exists('pictures/'.$filename.'.jpg'))
{
echo '<li style="margin:-3% 1% 1% 0%;"><img src="pictures/'.$filename.'.jpg" ><p class="usrname">'.$row['fname'].'</p>';
}
else if(file_exists('pictures/'.$filename.'.gif'))
{
echo '<li style="margin:-3% 1% 1% 0%;"><img src="pictures/'.$filename.'.gif" ><p class="usrname">'.$row['fname'].'</p>';
}
else if(file_exists('pictures/'.$filename.'.png'))
{
echo '<li style="margin:-3% 1% 1% 0%;"><img src="pictures/'.$filename.'.png" ><p class="usrname">'.$row['fname'].'</p>';
}
else
{
echo '<li style="margin:-3% 1% 1% 0%;"><img src="icons/user.png"><p class="usrname">'.$row['fname'].'</p>';
}
?>
<ul>
<li>My Profile</li>
<li>My submissions</li>
</ul>
</li>
<li style=" margin:-3% 1% 1% 0%;">Log Out</li>
</ul>
</div>
<div id="compete" class="compete" style="position:relative; top:5%;">
<div id="table-wrapper" class="table-wrapper">
<h2> Selct a course </h2>
<?php
echo '<form id="queryform" name="queryform">';
$result1=mysql_query("SELECT * from `student-course` WHERE studentid='$row[studentid]'");
while($row1=mysql_fetch_assoc($result1))
{
$sql="SELECT * from courses where courseid='$row1[courseid]'";
$answer=mysql_query($sql);
$row2=mysql_fetch_assoc($answer);
echo '<input type="radio" name="courses" value="'.$row2['courseid'].'" onchange="this.form.submit()">'.$row2['coursename'];
}
?>
</form>
</div>
</div>
<div id="showprevioussubmissions">
</div>
<script>
$("#queryform").submit(function(event) {
event.preventDefault();
alert("In the query");
var posting = $.post("previous-grades-student-script.php", $("#queryform").serialize());
posting.done(function(data) {
alert("In the success function");
var content = $(data).find('#showprevioussubmissions');
$("#showprevioussubmissions").html(data);
});
});
});
</script>
</body>
</html>
You will need to write jQuery code inside of $(function(){ /code goes here/ });
<script>
$(function(){
$("#queryform").submit(function(event) {
event.preventDefault();
alert("In the query");
var posting = $.post("previous-grades-student-script.php", $("#queryform").serialize());
posting.done(function(data) {
alert("In the success function");
var content = $(data).find('#showprevioussubmissions');
$("#showprevioussubmissions").html(data);
});
});
});
</script>
Combine section as single element.
<head>
<meta charset="utf-8">
<title>Competitions</title>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href='//www.google.com/fonts#UsePlace:use/Collection:Bree+Serif' rel='stylesheet' type='text/css'>
</head>
You are running the code to add the event handler in the head of the page, before any forms exist. Therefore $("#queryform") will be an empty collection of elements and no handlers will be added. You should either put the code at the end of the body, or wrap it in a document ready, so that it will be executed after the form element has been created:
<head>
<script>
// call the function on document ready
$(function() {
$("#queryform").submit(function(event) {
// code as before
});
})
</script>
</head>
Related
please i always stuck with javascript that can't run in my php. i wanna change the background color on class one-container if the data on class one >= 100. the data come from db that i connect with my php.
any help would be appreciated.
thanks and sorry for my bad english
<!DOCTYPE html>
<html lang="eng">
<head>
<title>Dashboard</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="body-container">
<div class="sec-nav-container">
<div class="wrapper">
<nav>
<div class="title">
<span class="dashboard">Dashboard Billing</span>
</div>
<div class="time-container">
<b class="last-updated">Last Updated on:</b>
<script type="text/javascript">
function lastModified () {
document.write(document.lastModified);
}
lastModified();
</script>
</div>
</nav>
</div>
</div>
<div class="header-container">
<div class="wrapper">
<?php
include "connect_db.php";
$sql = "SELECT * FROM tb_dashboard";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "
<div class='one-container'>
<h1 class='one'>" . $row['kirim_mpn'] . "</h1>
<p class='mpn'>Siap Kirim MPN</p>
</div>";
}
}
else {
echo "Tidak ada hasil";
}
mysqli_close($conn);
?>
</div>
</div>
</div>
</div>
<script src="main.js"></script>
<script language="JavaScript" src="emil.js" type="text/javascript"></script>
</body>
</html>
and this is raw code of javascript that i wanna use in my php
<script>
var colorBox = function () {
var data = [100];
if (data >= 100) {
document.getElementById("one-container").style.backgroundColor = '#FF6C60';
} else {
document.getElementById("one-container").style.backgroundColor = '#F8D347';
}
}
colorBox();>
</script>
i wanna make var data = [100] become var data = [" . $row['kirim_mpn'] . "]
I am making a web with information from a MySQL database and I want pictures to appear after clicking a buttom.
echo "<img align=\"left\"src=\"".$path[$y]."\" alt=\"error\">";
echo "<img align=\"right\"src=\"".$path_edit[$y]."\" alt=\"error\" id=\"$id[$y]\" style=\"visibility:hidden\">";
echo "_____________________________________";
echo "<script type=\"text/javascript\">";
echo "function showImage() {
document.getElementById(\"$id[$y]\").style.visibility=\"visible\";
}";
echo "</script>";
echo "<br><br>";
echo "<input type=\"button\" onclick=\"showImage();\" value=\"Show Picture\"/>";
echo "<p>";
I want the second image(The one with $PATH_edit[$y]) to appear after clicking in its buttom. (The buttom appears after each couple of images).
I have all with echo because It's all in the loop and I want it all to display as many times as number of entrances the database has.
I know I can not use the php variables in Javascript, I tried everything but I can't fix it. I am new with php, html and I have no idea ofJavaScript.
This is how it looks like without clicking the buttom
I know I can put an id to the image but that will only work for the first one.
This is how it looks like after clicking
I have also tried this:
echo "function showImage() {
var id_id = \"$id[$y]\";
document.getElementById(id_id).style.visibility=\"visible\";
}";
This is the whole code:
<!DOCTYPE html>
<!--- basic page needs
================================================== -->
<meta charset="utf-8">
<title>Base de Datos ATLAS</title>
<meta name="Una gran base de datos de microscopía" content="">
<meta name="Pablo Cruz" content="">
<!-- mobile specific metas
================================================== -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- CSS
================================================== -->
<link rel="stylesheet" href="css/base.css">
<link rel="stylesheet" href="css/vendor.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="style.css">
<!-- script (I tried to put the function here, bu tit does not work either)
================================================== -->
<script src="js/modernizr.js"></script>
<!-- favicons
================================================== -->
<link rel="shortcut icon" href="logo.jpg" type="image/x-icon">
<link rel="icon" href="logo.jpg" type="image/x-icon">
<!-- preloader
================================================== -->
<div id="preloader">
<div id="loader" class="dots-fade">
<div></div>
<div></div>
<div></div>
</div>
</div>
<!-- header
================================================== -->
<header class="s-header header">
<div class="header__logo">
<a class="logo" href="index.html">
<img src="images/logo_sin.png" alt="Homepage" >
</a>
</div> <!-- end header__logo -->
</div> <!-- end header__search -->
<a class="header__toggle-menu" href="#0" title="Menu"><span>Menu</span></a>
<nav class="header__nav-wrap">
<h2 class="header__nav-heading h6">Navigate to</h2>
<ul class="header__nav">
<li class="current">Inicio</li>
<li class="has-children">
Base de Datos
<ul class="sub-menu">
<li>Microscopía Electrónica</li>
<li>Microscopía Óptica</li>
</ul>
</li>
<li class="has-children">
Almacén
<ul class="sub-menu">
<li>Mitocondrias</li>
<li>Núcleo</li>
<li>Lisosomas</li>
<li>Vesículas</li>
<li>Aparato de Golgi</li>
<li>Microtubulos</li>
<li>Retículo Endosplamático Rugoso</li>
<!--
<ul class="sub-menu">
<li>Video Post</li>
<li>Audio Post</li>
<li>Standard Post</li>
</ul>
-->
</ul>
</li>
<li>USAL</li>
<li>Contacto</li>
</ul> <!-- end header__nav -->
Close
</nav> <!-- end header__nav-wrap -->
</header> <!-- s-header -->
<!-- s-content
================================================== -->
<section class="s-content s-content--top-padding s-content--narrow">
<article class="row entry format-standard">
<div class="entry__header col-full">
<h1 class="entry__header-title display-1">
Galeria de Mitocondrias.
</h1>
</div>
<?PHP
require "connect.php";
$x=0;
$y=0;
$autosuma = 222;
$database = "tfg";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM id_organulo WHERE mitocondria = 1";
$result = mysqli_query($db_handle, $SQL);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$id[$x] = $db_field['id'];
$comentario[$x] = $db_field['comentario'];
$nombre_de_foto[$x] = $db_field['nombre_de_foto'];
$autor[$x] = $db_field['autor'];
$path[$x] = $db_field['PATH'];
$path_edit[$x] = $db_field['PATH_edit'];
$ruta_perfil_foto[$x] = $db_field['ruta_perfil_foto'];
$x = $x+1;
echo "<div class=\"col-full entry__main\">";
echo "<div class=\"entry__author\">";
echo "<img src=\"".$ruta_perfil_foto[$y]."\"alt=\"\">";
echo "<div class=\"entry__author-about\">";
echo "<h5 class=\"entry__author-name\">";
echo "<span>$autor[$y]</span>";
echo "$nombre_de_foto[$y]";
echo "</h5>";
echo "</div>";
echo "</div>";
echo "<br>";
echo "</div>"; // <!-- s-entry__main -->
echo "<center>";
echo "<img align=\"left\"src=\"".$path[$y]."\" alt=\"error\">";
echo "<img align=\"right\"src=\"".$path_edit[$y]."\" alt=\"error\" id=\"$id[$y]\" style=\"visibility:hidden\">";
echo "_____________________________________";
echo "<br><br>";
echo '<input type="button" onclick="showImage('.$id[$y].');" value="Show Picture"/>';
echo "<p>";
print $comentario[$y];
echo "</p>";
echo "</center>";
$y++;
}
}
else {
print "Database NOT Found ";
}
mysqli_close($db_handle);
?>
<script type=\"text/javascript\">
function showImage() {
var id = <?php echo (json_encode($id[$y])); ?>;
document.getElementById(id).style.visibility="visible";
}
</script>";
<div class="row pagination-wrap">
<div class="col-full">
<nav class="pgn" data-aos="fade-up">
<ul>
<li><a class="pgn__prev" href="s_mitocondrias_result_3.php">Prev</a></li>
<li><a class="pgn__num" href="s_mitocondrias_result_1.php">1</a></li>
<li><a class="pgn__num" href="s_mitocondrias_result_2.php">2</a></li>
<li><a class="pgn__num" href="s_mitocondrias_result_3.php">3</a></li>
<li><span class="pgn__num current">4</span></li>
>
</ul>
</nav>
<hr>
</div>
</div>
<p> <h5>Codigo de rotulación:</h5> </p>
M: Mitocondrias <br>
dM: Doble membrana <br>
cM: Cresta Mitocondrial <br>
R: Ribosomas <br>
N: Nucleo <br>
eu: Eucromatina <br>
Nu: Nucleolo <br>
Mtu: Microtúbulos <br>
Ec: Esterocilio <br>
</p>
</center>
<?php $y++; ?>
</article> <!-- end entry/article -->
Thank you in advance.
first a little advice, separate php, javascript and html. Together it is difficult to read and maintain. Otherwise you create a function at each pass of the loop. It doesn't bother me that nothing works like that. Try it like this:
Send the id of your image as a parameter to the function. A single function, which will be after the loop.
function showImage(id) {
document.getElementById(id).style.visibility="visible";
}
and at each passage of the loop send to the function the id of the image like this :
<input type="button" onclick="showImage(\"$id[$y]\");" value="Show Picture">
Finally it will give something like that :
<?php
while(...){
echo '<img align="left" src="'.$path[$y].'" alt="error">';
echo '<img align="right" src="'.$path_edit[$y].'" alt="error" id="'.$id[$y].'" style="visibility:hidden">';
echo '_____________________________________';
echo '<br><br>';
echo '<input type="button" onclick="showImage('.$id[$y].');" value="Show Picture">';
echo '<p>';
}
?>
<script type="text/javascript">
function showImage(id) {
document.getElementById(id).style.visibility="visible";
}
</script>
Use ' for echo and not " when displaying html, it's more practical.
Good luck for the future
I want to alert the name of the item whose place bid button I will click but my code seems to alert only laptop. Can anyone tell me how to get div values that are dynamically generated through a php script. Below is the code for the page.I want to alert name of that item whose place bid I click on. Since the page is dynamically generated which gets item details from a database containing item details.
<?php
$con = mysqli_connect("localhost","root","*****","bidding") or
die(mysqli_error($con));
$select_query = "select * from items";
$select_query_result = mysqli_query($con, $select_query) or
die("Query Mistake");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bid</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="materialize/css/materialize.css"/>
<link rel="stylesheet" type="text/css" href="seperate2.css">
<script src="jquery-3.2.1.min.js"></script>
<script src="materialize/js/materialize.min.js"></script>
<script type="text/javascript">
function post_data(){
var item_name = document.getElementById("item_name").innerHTML;
alert(item_name);
}
</script>
</head>
<body>
<div class="container">
<h1>Bid</h1>
<div class="row">
<?php while($row = mysqli_fetch_array($select_query_result)) { ?>
<div class="col s3" >
<div id="item_name"><?php echo"$row[item_name]"?></div>
<div id="starting_price"><?php echo"$row[starting_price]"?</div>
<div><?php echo"$row[description]"?></div>
<button class="btn waves-effect waves-teal"
onclick="post_data()">Place Bid</button>
</div>
<?php } ?>
</div>
</div>
</body>
</html>
ID of element in HTML must be unique. Use class.
In loop you declare static name of ID, that are not unique.
Your code requires a counter by which the dynamically created DIVs may be accessed. Your <div class="row"> block would be:
<div class="row">
<?php
$divCounter = 0;
while($row = mysqli_fetch_array($select_query_result)) {
$divCounter += 1;
?>
<div class="col s3" >
<div id="item_name<?php echo $divCounter; ?>"><?php echo"$row[item_name]"?></div>
<div id="starting_price"><?php echo"$row[starting_price]"?</div>
<div><?php echo"$row[description]"?></div>
<button class="btn waves-effect waves-teal"
onclick="post_data('<?php echo 'item_name'.$divCounter; ?>')">Place Bid</button>
</div>
<?php } ?>
</div>
Notice that the call to the Javascript function post_data() now provides the DIV id that contains its counter. To complete the job, adjust post_data() to include the parameter:
<script type="text/javascript">
function post_data(divId){
var item_name = document.getElementById(divId).innerHTML;
alert(item_name);
}
</script>
If you prefer, instead of using a counter and concatenating with the static "item_name", you may use the $row[item_name] property instead. Whether or not you can do this will depend on whether this property can serve as a valid HTML id attribute value.
I have a loop that retrieves the values from the database and puts it into a unordered list. What I want to do is to retrieve the value of the title within the same list element.
By saying this I mean, I want to get "This is a title" when I click the first link and get "This is title number two" when clicking the second link and so on. I tried using $(this).parent().text() but it returns "undefined"...
<ul>
<li>
<h3 class="title">This is a title number two</h3>
Delete
<li>
<li>
<h3 class="title">This is a title</h3>
Delete
<li>
</ul>
Here's the full script:
<?php
require_once('db.php');
$sql = "SELECT id, name, user, done, created FROM todos";
$result = mysqli_query($conn, $sql);
$id = $_GET['id'];
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Todo App</title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script language="JavaScript" type="text/javascript">
function checkDelete(event){
var item_name = $('#title').text();
var answer = confirm("Delete " + item_name + "?");
if(!answer){
event.preventDefault();
return false;
}
}
</script>
</head>
<body>
<div class="items">
<h2>Your todo list</h2>
<ul>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<li>' . '<p id="title">' . $row['name']. '</p>' .'<a href=delete.php?id='. $row['id'] .' onClick=checkDelete(event)>Delete</a>';
echo '<a class="update" href=todo.php?id='.$row['id'].'&name=' . urlencode($row['name']) .'>Update</a></li>';
}
} else {
echo "0 results";
}
$conn->close();
?>
</ul>
</div>
<form id="todo" action="addtodo.php" method="post">
<label for="item">Add</label>
<input type="text" name="item" id="item">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Using
$(this).parent().text()
won't work because $(this).parent() is going to select the <li> element, which doesn't have any value set for .text()
Select the a tag and set an on click event listener and get the previous element's value
$('a').on('click', function() {
var title = $(this).prev().text();
});
$(document).ready(function(){
$('.title').on('click',function(){
alert($(this).siblings('h3').html());
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
<li>
<h3>This is a title number two</h3>
<a class="title" href="#">Delete</a>
<li>
<li>
<h3>This is a title</h3>
<a class="title" href="#">Delete</a>
<li>
</ul>
I started with modifing the header on my site, and have a hard time to make it worked as i wanted.
I want, header background to change background color to white, when scroll down 100-150px, exactly like is on this site.
I found this JS:
$(function(){
$('#header_nav').data('size','big');
});
$(window).scroll(function(){
if($(document).scrollTop() > 0) {
if($('#header_nav').data('size') == 'big') {
$('#header_nav').data('size','small');
$('#header_nav').stop().animate({
height:'40px'
},600);
}
}
else {
if($('#header_nav').data('size') == 'small') {
$('#header_nav').data('size','big');
$('#header_nav').stop().animate({
height:'100px'
},600);
}
}});
what i inserted into custom JS plugin in my WP site.
Also have this JS:
<script>
$(window).on("scroll", function() {
if ($(this).scrollTop() > 100) {
$("header").css("background","#252525");
}
else {
$("header").css("background","#fff");
}
});
</script>
Is maybe this better sollution, then previous code?
How to use this JS to make the effect on demo site i posted before in this post?
use following code snippet, working fine in the demo website
jQuery(document).scroll(function(){
if(jQuery(this).scrollTop() > 300)
{
jQuery('#navigation').css({"background":"red"});
} else {
jQuery('#navigation').css({"background":"transparent"});
}
});
Try this code.
$(function() {
var bgcolor_navigation = function(){
var bg_offset_top = $(window).scrollTop(); // our current vertical position from the top
if ((100 > bg_offset_top) &&(150 < bg_offset_top)) {
$('#navigation').addClass("bgcolorheadnav");
} else {
$('#navigation').removeClass("bgcolorheadnav");
}
};
// run our function on load
bgcolor_navigation();
// and run it again every time you scroll
$(window).scroll(function() {
bgcolor_navigation();
});
});
css
.bgcolorheadnav{
background-color:#000;
}
This is just for websites made by WordPress:
Create a child theme for your theme.
Activate your child theme.
Copy your header.php file to the child theme folder by FTP client
Replace the code in the child’s header.php with this code:
<?php
/**
* The Header for our theme
*
* Displays all of the <head> section and everything up till <div id="main">
*
* #package WordPress
* #subpackage Twenty_Fourteen
* #since Twenty Fourteen 1.0
*/
?><!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 7) & !(IE 8)]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width">
<title><?php wp_title( '|', true, 'right' ); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script>
<![endif]-->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).bind('scroll', function() {
var distance = 50;
if ($(window).scrollTop() > distance) {
$('.header-main').addClass('scrolled');
}
else {
$('.header-main').removeClass('scrolled');
}
});
});
</script>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed site">
<?php if ( get_header_image() ) : ?>
<div id="site-header">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<img src="<?php header_image(); ?>" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>">
</a>
</div>
<?php endif; ?>
<header id="masthead" class="site-header" role="banner">
<div class="header-main">
<h1 class="site-title"><?php bloginfo( 'name' ); ?></h1>
<div class="search-toggle">
<?php _e( 'Search', 'twentyfourteen' ); ?>
</div>
<nav id="primary-navigation" class="site-navigation primary-navigation" role="navigation">
<button class="menu-toggle"><?php _e( 'Primary Menu', 'twentyfourteen' ); ?></button>
<a class="screen-reader-text skip-link" href="#content"><?php _e( 'Skip to content', 'twentyfourteen' ); ?></a>
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu', 'menu_id' => 'primary-menu' ) ); ?>
</nav>
</div>
<div id="search-container" class="search-box-wrapper hide">
<div class="search-box">
<?php get_search_form(); ?>
</div>
</div>
</header><!-- #masthead -->
<div id="main" class="site-main">
Put following code to your Child Theme style.css file or install the Simple Custom CSS plugin and put the code there.
.header-main {
transition:top 0.5s ease;
box-shadow:0 0 10px black;
transition: background-color 0.5s ease;
}
.scrolled {
background: #bada55!important;
}
If you don't do the CSS this way and put the code to themes -> style.css, you will loose all changes you made when you update your theme in the future.
The site you referred uses bootstrap framework.
You can see what is done on that site by right clicking on the site and say inspect element. The following code was found for the navbar: This way you do not need to write custom js, jut follow the industry the best practice.
<nav class="navbar navbar-dark navbar-fixed-top top-nav-collapse" role="navigation">
<div class="navbar-container">
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
<i class="fa fa-bars"></i>
</button>
<a class="navbar-brand" href="/">
<span class="logo hidden-xs">
<img src="img/logo-santa.svg" alt="">
</span>
<span class="logo hidden-sm hidden-md hidden-lg">
<img src="img/logo-notext.svg" alt="">
</span>
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-right navbar-main-collapse">
<ul class="nav navbar-nav">
<!-- Hidden li included to remove active class from about link when scrolled up past about section -->
<li class="hidden active">
</li>
<li class="page-scroll">
Pricing
</li>
<li class="page-scroll">
XenoPanel
</li>
<li class="page-scroll">
Multicraft
</li>
<li class="page-scroll navbar-borderbtnn">
Client Area <i class="fa fa-arrow-circle-right" aria-hidden="true"></i>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>