Imported file is undefined - javascript

Solution
My question was asked with little knowledge in HTML and JavaScript, I apologize for this. With more experience I can clearly see that this was not a good question asked, anyway the solution to my question was simply that the source file was not in the corresponding library.
The thing is, when I click on "live preview" in brackets IDE, I can see the dynamic diagram I have created, but when I double click on the index.html file, it is showing the navigation bar, but not the dynamic chart....So the difference is:
- Live priview: is showing the navigation-bar with the dynamic chart
- Double click on index.html: showing just the navigation-bar without the dynamic chart....?
Btw: I have also tested this in localhost with xamp, same problem there with no dynamic chart...
Here is my code: index.html:
<!DOCTYPE html>
<html>
<head>
<!-- Unable to zooming device -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
<!-- Initialize jquery -->
<script src="js/jquery-2.1.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Link to stylesheet bootstrap.css -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<!--Live Random Data -->
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Live Random Data"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="/canvasjs/canvasjs.min.js"></script>
</head> <!-- End header-->
<body>
<nav class = "navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"> </span>
<span class="icon-bar"></span>
</button>
<a style = "color:red;"class="navbar-brand" href="#">KPEC</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><span class="glyphicon glyphicon-home" style="font-size:25px;" aria-hidden="true"></span></li>
<li><span class="glyphicon glyphicon-edit" style="font-size:25px;" aria-hidden="true"></span></li>
<li><span class="glyphicon glyphicon-stats" style="font-size:25px;" aria-hidden="true"></span></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-list-alt" style="font-size:25px;" aria-hidden="true"></span></li>
<li class="dropdown">
<span class="glyphicon glyphicon-cog" style="font-size:25px;" aria-hidden="true"></span><span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>5</li>
<li>6</li>
<li>7</li>
<li class="divider"></li>
<li>8</li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav><!-- end navbar -->
<!--Window Size Of Realtime Data-->
<div id="chartContainer" style="height: 300px; width:100%;"></div>
</body> <!-- End body-->
</html><!-- End html-->

I think the path of your dependancies are not correct, some time you ahve it relative, sometime not.
Try to put the absolutes one in relative? eg replace
<script type="text/javascript" src="/canvasjs/canvasjs.min.js"></script>
to
<script type="text/javascript" src="canvasjs/canvasjs.min.js"></script>

Related

Bootstrap styles suddenly stopped working

Questions I've already looked at:
Bootstrap JavaScript not working
twitter bootstrap drop down suddenly not working
Complete list of reasons why a css file might not be working
My Bootstrap styles seem to have suddenly stopped being applied, resulting in pages that look something like this. I'm using the layout generated by ASP.NET MVC 5, so there should be a navbar at the top, among other things. Ignore the red banner, the button doesn't show on that page anyway.
Nothing looks amiss in the dev tools -- console, network, etc. all look normal with no errors. All the files are loaded, and changing their order changes nothing. All of the .css and .js files are loaded from the local file system. I even reverted to a commit from yesterday, when the site was working fine, but the site still displays incorrectly.
I've tried turning it off and on again, now I'm out of ideas.
Edit: Same results, no matter the browser. I'm at a total loss here.
Code, as requested:
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Log in</title>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/Site.css" rel="stylesheet"/>
<link href="/Content/css/select2.css" rel="stylesheet"/>
<link href="/Content/alertify.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.6.2.js"></script>
<script src="/Scripts/modernizr-2.8.3.js"></script>
<script src="/Scripts/jquery-3.1.1.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>
<script src="/Scripts/alertify.js"></script>
<script src="/Scripts/Custom/JavaScript/utility.js"></script>
<script src="/Scripts/jquery.mask.js"></script>
<script src="/Scripts/autosize.js"></script>
<script src="/Scripts/Custom/register-modal.js"></script>
<script>
//<!-- Google Analytics -->
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'shh', 'none');
ga('send', 'pageview');
//<!-- End Google Analytics -->
</script>
<!-- FontAwesome -->
<link href="/Content/FontAwesome/fontawesome-all.css" rel="stylesheet" />
</head>
</html>
change the <nav> tag in layout file with this
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor01">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
tl;dr OP updated from Bootstrap 3 -> 4 without updating HTML.
A week ago, I updated to Bootstrap v4(a?) via NuGet, without paying attention to the change in major version number. Apparently my cache didn't get cleared until a week later (when I asked this question), so I had forgotten the update even happened.
Bootstrap 4 is a major rework, so the bulk of my Bootstrap HTML became invalid.
Reverting Bootstrap fixes everything.

JavaScript Print function issue

When I clicked Ön Izleme (Span/Button) , i come the back i cant use my JavaScript Function Like Draggable Resize method on my divs. Do anyone can help me ? Önizleme Button job is print
When i back to from print screen i cant use my JavaScript function Like Draggable and resize. What is the my fault do anyone can help me?
<!DOCTYPE html>
<html>
<head>
<style>
.divKolon {width:50px;height:50px;padding:10px;border:3px solid #DD4B39; background-color: #E98A7E;float:left;}
.divKolon-resizable-e{
height: 50px !important;
}
.divUstKolon {width:50px;height:50px;padding:10px;border:3px solid #DD4B39; text-align:center;float:left;margin-right:20px;}
.shadow(#shadow){
-webkit-box-shadow:#shadow;
-mox-box-shadow:#shadow;
box-shadow:#shadow;
}
.label-danger{
margin-left:10px;
margin-top:10px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
var Bosluk=0;
var SecilenItem;
var VTBilgileri=[];
var YaziFont;
var YaziBoyutu;
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
//console.log(ev.target);
}
function drop(ev) {
ev.stopPropagation()
var EklenecekDiv=ev.target;
var data = ev.dataTransfer.getData("text");
//console.log(ev.target);
console.log($(ev.target).parent());
var divim=ev.target;
var c = divim.children;
console.log(c.lenght);
/*if(c[2]==null)
{
EklenecekDiv=$($(ev.target).parent());
EklenecekDiv.append()
var label1=document.getElementById(data);
var MyLabelAdd1=document.createElement("div");
MyLabelAdd1.appendChild(document.createTextNode($(label1).html()));
$(MyLabelAdd1).attr("name","KolonAdi");
EklenecekDiv.append(MyLabelAdd1);
divim.remove();
label1.remove();
return;
console.log(EklenecekDiv);
}
if(c[3]!=null)
{
c[3].remove();
}*/
var label=document.getElementById(data);
var MyLabelAdd=document.createElement("div");
MyLabelAdd.appendChild(document.createTextNode($(label).html()));
$(MyLabelAdd).attr("name","KolonAdi");
if(YaziFont!=null&&YaziBoyutu!=null){MyLabelAdd.style.fontFamily=YaziFont; }
if(YaziBoyutu!=null){alert(YaziBoyutu); MyLabelAdd.style.fontSize =YaziBoyutu+"px"; }
EklenecekDiv.appendChild(MyLabelAdd);
label.remove();
}
function tiklandi()
{
alert("Okey");
}
function Click(e){
if(SecilenItem==null)
{
alert("Lütfen Alan Seçiniz");
return;
}
var item=SecilenItem;
var div=document.getElementById("Itemler");
var label=document.createElement("span");
$(label).addClass("label label-danger col-xs-1");
$(label).attr("id","drag");
$(label).attr("draggable","true");
$(label).attr("ondragstart","drag(event)");
$(label).mousedown(function(e){
if( e.button == 2 ) {
$(this).remove();
return false;
}
return true;
});
label.appendChild(document.createTextNode(item));
div.appendChild(label);
//console.log($(label).html());
var KolonDiv=document.createElement("div");
$(KolonDiv).attr("ondrop","drop(event)")
$(KolonDiv).attr("ondragover","allowDrop(event)");
$(KolonDiv).addClass("divKolon");
KolonDiv.style.marginLeft=Bosluk+"px";
$(KolonDiv).mousedown(function(e){
if( e.button == 2 ) {
$(this).remove();
return false;
}
return true;
});
$(KolonDiv).resizable();
$(KolonDiv).draggable();
var Kolonlar=document.getElementById("Kolonlar");
Kolonlar.appendChild(KolonDiv);
};
function CiktiGetir(e){
var KolonlarinChildren=document.getElementsByClassName("divKolon");
var printContents = document.getElementById("Kolonlar");
var originalContents = document.body.innerHTML;
printContents=printContents.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
function TabloAlanTiklandi (e){
SecilenItem=$(e).text();
$(e).parents(".dropdown").find('.btn').html( $(e).text() );
//e.remove();
}
function FontLi(e)
{
YaziFont=$(e).text();
$(e).parents(".dropdown").find('.btn').html( $(e).text() );
}
function StilDegistir(e)
{
}
function EkAlanClick(e){
if($("#EkAlan").val()==null)
{
alert("Lütfen Alan Giriniz");
return;
}
var h1=document.createElement("h1");
var item=$("#EkAlan").val();
var div=document.getElementById("Itemler");
var label=document.createElement("span");
$(label).addClass("label label-danger col-xs-1");
$(label).attr("id","drag");
$(label).attr("draggable","true");
$(label).attr("ondragstart","drag(event)");
$(label).mousedown(function(e){
if( e.button == 2 ) {
$(this).remove();
return false;
}
return true;
});
label.appendChild(document.createTextNode(item));
div.appendChild(label);
//console.log($(label).html());
var KolonDiv=document.createElement("div");
$(KolonDiv).attr("ondrop","drop(event)")
$(KolonDiv).attr("ondragover","allowDrop(event)");
$(KolonDiv).addClass("divKolon");
$(KolonDiv).mousedown(function(e){
if( e.button == 2 ) {
$(this).remove();
return false;
}
return true;
});
$(KolonDiv).resizable();
$(KolonDiv).draggable();
var Kolonlar=document.getElementById("Kolonlar");
Kolonlar.appendChild(KolonDiv);
$("#EkAlan").val("");
}
function BoslukEkle(e)
{
if($("#Aralik").val().lenght==0)
{
alert("Aralik Degeri Giriniz");
return;
}
Bosluk=$("#Aralik").val();
alert(Bosluk);
$("#Aralik").val("");
}
function BoyutEkle(e)
{
if($("#YaziBoyutu").val().lenght==0)
{
alert("Boyut Degeri Giriniz");
return;
}
YaziBoyutu=$("#YaziBoyutu").val();
$("#YaziBoyutu").val("");
}
</script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AdminLTE 2 | Calendar</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<!-- Font Awesome -->
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition skin-blue sidebar-mini">
<!-- Left side column. contains the logo and sidebar -->
<!-- Content Wrapper. Contains page content -->
<!-- Content Header (Page header) -->
<!-- Main content -->
<div class="divUstKolon col-xs-12" id="Itemler" style="height:50px"></div>
<div class=" col-xs-12" style="margin-top:20px" >
<div class="dropdown col-xs-1" style="height:32px " >
<button class="btn btn-danger dropdown-toggle" type="button" data-toggle="dropdown">Alan Ekle
<span class="caret"></span></button>
<ul id="Secenekler" class="dropdown-menu">
<li><a onClick="TabloAlanTiklandi(this)" href="#">Isim</a></li>
<li><a onClick="TabloAlanTiklandi(this)"href="#">SoyIsim</a></li>
<li><a onClick="TabloAlanTiklandi(this)" href="#">Adress</a></li>
<li><a onClick="TabloAlanTiklandi(this)" href="#">Numara</a></li>
<li><a onClick="TabloAlanTiklandi(this)" href="#">Yaş</a></li>
<li><a onClick="TabloAlanTiklandi(this)" href="#">Tanıdık 1</a></li>
</ul>
</div>
<label class="btn btn-default col-xs-1" style="margin-left :10px ; height:32px " id="Ekle" onClick="Click(this)"> Ekle </label>
<div class="col-xs-1"></div>
<input style="margin-left :10px ; height:32px " type="text" class="col-xs-1" id="EkAlan">
<label style="margin-left :10px ; height:32px" class="btn btn-default col-xs-1" id="Ekle" onClick="EkAlanClick(this)"> Ek Alan Ekle </label>
<div class="col-xs-4" ></div>
<label class="btn btn-danger col-xs-1" id="CiktiGetir" style="margin-right :10px" onClick="CiktiGetir(this)" >Ön İzleme</label>
<label class="btn btn-primary col-xs-1" id="CiktiGetir" style="margin-right :10px" onClick="CiktiGetir(this)" >Ana Sayfa</label>
</div>
<div class="col-xs-12" style="margin-top:10px">
<input style="margin-left :10px ; height:32px " type="text" class="col-xs-1" id="YaziBoyutu" placeholder="Yazı Boyutu">
<label style="margin-left :10px ; height:32px" class="btn btn-default col-xs-1" onClick="BoyutEkle(this)"> Değiştir</label>
<div class="col-xs-1" ></div>
<div class="dropdown col-xs-2" style="height:32px " >
<button class="btn btn-danger dropdown-toggle" type="button" data-toggle="dropdown">Yazı Font
<span class="caret"></span></button>
<ul id="Fontlar" class="dropdown-menu">
<li><a onClick="FontLi(this)" href="#">Georgia</a></li>
<li><a onClick="FontLi(this)"href="#">Palatino Linotype</a></li>
<li><a onClick="FontLi(this)" href="#">Book Antiqua</a></li>
<li><a onClick="FontLi(this)" href="#">Times New Roman</a></li>
<li><a onClick="FontLi(this)" href="#">Arial</a></li>
<li><a onClick="FontLi(this)" href="#">Helvetica</a></li>
<li><a onClick="FontLi(this)" href="#">Arial Black</a></li>
<li><a onClick="FontLi(this)" href="#">Impact</a></li>
<li><a onClick="FontLi(this)" href="#">Lucida Sans Unicode</a></li>
<li><a onClick="FontLi(this)" href="#">Tahoma</a></li>
<li><a onClick="FontLi(this)" href="#">Verdana</a></li>
<li><a onClick="FontLi(this)" href="#">Courier New</a></li>
<li><a onClick="FontLi(this)" href="#">Lucida Console</a></li>
</ul>
</div>
<label style="margin-left :10px ; height:32px" class="btn btn-default col-xs-1" id="Ekle" onClick="StilDegistir(this)"> Yazi Stil Değiştir</label>
<div class="col-xs-1" ></div>
</div>
<div class="col-xs-12" id="Kolonlar" style="margin-top :10px"> </div>
<!-- /.content -->
<!-- /.content-wrapper -->
<!-- Control Sidebar -->
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
<!-- ./wrapper -->
<!-- jQuery 2.2.3 -->
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Slimscroll -->
<script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/app.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="dist/js/demo.js"></script>
<!-- fullCalendar 2.2.5 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script src="plugins/fullcalendar/fullcalendar.min.js"></script>
<!-- Page specific script -->
</body>
</html>
It's not an optimal solution but can you try replacing CiktiGetir function with this:
function CiktiGetir(e){
var htmlElement = document.querySelector("html");
var printContents = document.getElementById("Kolonlar");
// Make body invisible, append new element to HTML
document.body.style.display = "none";
htmlElement.appendChild(printContents);
window.print();
// Make body visible again, remove the added element
document.body.style.display = "initial";
htmlElement.removeChild(printContents);
}
Replacing HTML content breaks the JS events and dynamic contents.
You are replacing the body HTML
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
So you will need to reatach the events.
Try the "on" jquery method. Something like
$(document).on('click', '#CiktiGetir', function() { CiktiGetir(); });
My code was just an example. You will have to adapt it to your code.
You need to reatach the events after replace body content.
If, you dont want to to this, you can refresh the entire page.
function CiktiGetir(e){
var KolonlarinChildren=document.getElementsByClassName("divKolon");
var printContents = document.getElementById("Kolonlar");
printContents=printContents.innerHTML;
document.body.innerHTML = printContents;
window.print();
location.reload();
}

(Bootstrap) - Changing dropdown button text to reflect item clicked removes caret

I am using the dropdown from bootstrap and i would like the button to have its text change depending on which of it's two dropdown items i click. The text changes according to the item clicked but the caret is gone after the first change and so forth. I want to keep the caret in the button!
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" value="Fast">Fast
<span class="caret"></span></button>
<ul class="dropdown-menu" value="Fast">
<li onclick="dropdown(this.innerHTML);">Fast</li>
<li onclick="dropdown(this.innerHTML);">Accurate</li>
</ul>
</div>
<script>
function dropdown(val){
var y = document.getElementsByClassName('btn btn-default dropdown-toggle');
var aNode = y[0].innerHTML=val;
}
</script>
With your current code, appending the caret icon code will help you retain it after changing the drop down value.
function dropdown(val) {
var y = document.getElementsByClassName('btn btn-default dropdown-toggle');
var aNode = y[0].innerHTML = val + ' <span class="caret"></span>'; // Append
}
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" value="Fast">Fast
<span class="caret"></span>
</button>
<ul class="dropdown-menu" value="Fast">
<li onclick="dropdown(this.innerHTML);">Fast</li>
<li onclick="dropdown(this.innerHTML);">Accurate</li>
</ul>
.innerHTML will get you the entire content, including the inner span that you are using for the caret.
What you need is the textContent of the firstchild of your dropdown, which is actually a textNode.
Example Snippet:
var dropdown = document.getElementsByClassName('dropdown-toggle')[0],
options = document.getElementsByClassName('dropdown-menu')[0]
;
options.addEventListener("click", function(e) {
if (e.target.tagName === 'A') {
dropdown.firstChild.textContent = e.target.textContent + ' ';
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div class="dropdown">
<button id="dropdownBtn" class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Fast <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>Fast</li>
<li>Accurate</li>
</ul>
</div>
This is happening because you're replacing the html with the value - the caret span is inside the button (so part of the html of the button), so also getting replaced.
As you're using bootstrap, which uses jquery, use jquery to make this easy:
function dropdown(val) {
$(".btn.dropdown-toggle").text(val)
}
You can save the caret inside a variable and add it back when you change the value.
As you are using bootstrap, you already have jQuery loaded in the page so let's do it this way:
Fiddle
$myDropdown = $('#MyDropdown');
$myDropdown.find("li").click(function(){
$caret = ' <span class="caret"></span>';
$val = $(this).html();
$(".btn.dropdown-toggle").html($val+$caret)
});
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" value="Fast">Fast
<span class="caret"></span></button>
<ul id="MyDropdown" class="dropdown-menu" value="Fast">
<li>Fast</li>
<li>Accurate</li>
</ul>
</div>
Use innerText in the dropdown function instead of innerHTML
<li onclick="dropdown(this.innerText);">Fast</li>
Change the content of the function to replace the textContent of the firstChild which holds the value of the button.
var aNode = y[0].firstChild.textContent = val;
function dropdown(val) {
var y = document.getElementsByClassName('btn btn-default dropdown-toggle');
var aNode = y[0].firstChild.textContent = val;
}
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" value="Fast">Fast
<span class="caret"></span>
</button>
<ul class="dropdown-menu" value="Fast">
<li onclick="dropdown(this.innerText);">Fast</li>
<li onclick="dropdown(this.innerText);">Accurate</li>
</ul>
This is the one and only permanent solution for bootstrap 3.This will work for all dropdown.
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" value="Fast">Fast
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Fast</li>
<li>Accurate</li>
</ul>
</div>
<script>
$(document).on('click','.dropdown-menu li',function(){
$(this).parent().parent().find('.dropdown-toggle').html($(this).html() + ' <span class="fa fa-caret-down"></span>');
});
</script>
You can try:
$(".dropdown-menu li a").click(function(){
$(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
$(this).parents(".dropdown").find('.btn').val($(this).data('value'));
});

Creating a directive for bootstrap menuItems

I have built a directive for some of the boilerplate in the bootstrap navbar with ng-transclude for the navbar-collapse.I also find that there are two types of li elements for the navbar-nav items depending on whether the menu item is a dropdown or not.I find that this dropdown is however,not working.
I have built my code here in the plunker .
My JS code looks like this:
var app = angular.module('app',[]);
app.controller('main',['$scope',function($scope){
$scope.navbarOptions = {
color:'inverse',
position:'fixed-top',
collapseTarget:'navbar-ex1-collapse',
brand:'My Login',
};
$scope.menuItems=[{title:'home'},{title:'projects'},{title:'pricing'},
{
title:'Stack',
dropdown:['Java','Ruby','Javascript','Go']
}];
}]);
app.directive('bootstrapNavbar',function(){
return {
restrict:'AE',
templateUrl:'navbar.html',
scope:{
options:"="
},
transclude:true,
};
});
app.directive('bootstrapMenuitem',function(){
return {
restrict:'EA',
templateUrl:'bootstrap-menuItem.html',
scope:{
item:"#"
},
link:function(scope,element,attrs){
console.log(scope);
console.log(element);
console.log(attrs);
}
}
});
My html templates look like this:
//navbar.html
<nav class="navbar navbar-{{options.color}} navbar-{{options.position}}" role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<!-- figure out a way to do toggle as an attribute directive -->
<button ng-show="options.collapseTarget" class="navbar-toggle" data-toggle="collapse" data-target=".{{options.collapseTarget}}">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">{{options.brand}}</a>
</div>
<div class="collapse navbar-collapse {{options.collapseTarget?options.collapseTarget:''}} navbar-body" ng-transclude>
</div><!-- /.navbar-collapse -->
</div>
</nav>
//bootstrap-menuItem.html
<li ng-hide="dropdown && dropdown.length">
{{item.title}}
</li>
<li ng-show="dropdown && dropdown.length" class="dropdown">
{{item.title}} <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="action in item.dropdown">{{action}}</li>
</ul>
</li>
This is my html:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Building a directive for horizontal-form using Bootstrap using Angular">
<link data-require="bootstrap#*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script data-require="jquery#*" data-semver="2.1.3" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.3.1" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script data-require="angular.js#*" data-semver="1.4.0-beta.2" src="https://code.angularjs.org/1.4.0-beta.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="main">
<nav options="navbarOptions" bootstrap-navbar>
<ul class="nav navbar-nav">
<bootstrap-menuitem ng-repeat="item in menuItems" item="{{item}}"></bootstrap-menuItem>
</ul>
</nav>
</body>
</html>
The question is how do I access the item inside bootstrap-menuitem?
The template seems unable to use the item although it is in the scope?
UPDATE:
The item property accessed on the scope is a string,it needs to be an object.How can I obtain a property in the controller scope on the scope of a nested directive?
Using item:"=" instead of # causes the error http://pastebin.com/e9NDVH5b .
I assume that when using = on the bootstrap-menuitem it takes the item from ng-repeat?
However,it causes {{item.title}} to show up on the page.
In your index.html, remove double brackets in attribute item,
<bootstrap-menuitem ng-repeat="item in menuItems" item="item"></bootstrap-menuItem>
Besides, in your bootstrapMenuitem, change scope item's declaration from item: "#" to item: "=":
app.directive('bootstrapMenuitem',function(){
return {
restrict:'EA',
templateUrl:'bootstrap-menuItem.html',
scope:{
item:"="
},
link:function(scope,element,attrs){
console.log(scope);
console.log(element);
console.log(attrs);
}
}
});
This way, item can be passed to your directive's template as an object instead of plain text string.

What am I doing wrong with this JavaScript parsing code?

I am trying to make a simplistic HTML editor for part of my website without things like Ace or TinyMCE. The problem is that when I'm using local storage, the save function appears to work, but the view function is not changing the notes to the saved notes.
I made a JSFiddle for all of you, at this URL.
Here is my HTML code:
<html>
<head>
<!-- Begin Section 1: Metas -->
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<!-- End Section 1: Metas -->
<!-- Begin Section 2: Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/nprogress/0.1.3/nprogress.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdn.mxpnl.com/libs/mixpanel-2.2.min.js" type="text/javascript"></script>
<script src="https://secure.quantserve.com/quant.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ladda-bootstrap/0.1.0/ladda.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ladda-bootstrap/0.1.0/spin.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.min.js" type="text/javascript"></script>
<script src="scripts/app/app.js" type="text/javascript"></script>
<!-- End Section 2: Scripts -->
<!-- Begin Section 3: Stylesheets and Links -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/nprogress/0.1.3/nprogress.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Pacifico|Open+Sans|Roboto|Roboto+Slab" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/ladda-bootstrap/0.1.0/ladda.min.css" rel="stylesheet" type="text/css">
<link href="stylesheets/app/app.css" rel="stylesheet" type="text/css">
<!-- End Section 3: Stylesheets and Links -->
<!-- Start Section 4: Required Elements -->
<title>Superpad Editor</title>
<!-- End Section 4: Required Elements -->
</head>
<body>
<div class="container animated bounce">
<div class="errors"></div>
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-brand-centered">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="navbar-brand navbar-brand-centered"><span class="brand-logo">Superpad</span></div>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-brand-centered">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="btn-group">
<button type="button" class="btn btn-primary" id="save">Save Notes</button>
<button type="button" class="btn btn-success" id="view">View Saved Notes</button>
</div>
<div contenteditable class="content-editable normal editor"></div>
</div>
</body>
</html>
Here is my JavaScript (it uses jQuery):
NProgress.start();
mixpanel.init("<CENSORED FOR SECURITY>");
mixpanel.track("Page Loads");
NProgress.done();
$(document).ready(function(){
if (Modernizr.localstorage) {
console.log("L.S.W.");
} else {
$(".errors").append("<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×<\/span><span class="sr-only">Close<\/span><\/button><strong>Oh snap!<\/strong> Local Storage doesn't work on your browser. Saving won't work, so you might want to keep this open if you want to keep your notes.<\/div>");
NProgress.done();
};
$("#save").click(function() {
localStorage["note"] = JSON.stringify($(".editor").html());
});
$("#view").click(function() {
if (localStorage["note"] != null) {
var contentsOfOldDiv = JSON.parse(localStorage["note"]);
$(".editor").
$("div.fifth").replaceWith(contentsOfOldDiv);
} else {
$(".errors").append("<div class=alert alert-info alert-dismissible> role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×<\/span><span class="sr-only">Close<\/span><\/button><strong>Heads up!<\/strong> No save was detected. Did you save before?<\/div>");
};
});
});
So what am I doing wrong (I got the JSON parsing idea from another Stack Overflow subject!)?
You have several syntax issues. For example the lines below:
$(".errors").append("<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×<\/span><span class="sr-only">Close<\/span><\/button><strong>Oh snap!<\/strong> Local Storage doesn't work on your browser. Saving won't work, so you might want to keep this open if you want to keep your notes.<\/div>");
and
$(".errors").append("<div class=alert alert-info alert-dismissible> role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×<\/span><span class="sr-only">Close<\/span><\/button><strong>Heads up!<\/strong> No save was detected. Did you save before?<\/div>");
You need to escape the " character or use a single quote. That might not solve your issue, but it's a start. Your code is failing when execution reaches that line, and it can't continue, which might explain why you aren't getting the expected result.
Try using your browser developer tools to find any errors in your code. This page has some information on finding and using the dev tools in your browser. The error in the JSFiddle is shown as:
Uncaught SyntaxError: Unexpected identifier
If you fix the quotation issues, you then get the error:
Uncaught ReferenceError: mixpanel is not defined
Keep going through the errors in your console and see if you can narrow down the issue that way.

Categories

Resources