Call JS function onclick - javascript

The sample code below loads a page with a "Show 3D" clickable div. Onclick, it should load a 3D viewer and display associated data.
function showPDB(path,id) {
var stage = new NGL.Stage(id, {backgroundColor:'white'});
stage.loadFile(path).then(function (o) {
o.addRepresentation("cartoon", {color: 'white' });
o.autoView();
});
};
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/ngl#latest/dist/ngl.min.js"></script>
</head>
<body>
<div class="row">
<div class="col" data-toggle="collapse" data-target="#show_0" id="_show_0" onclick="showPDB('https://alphafold.ebi.ac.uk/files/AF-P08047-F1-model_v4.pdb', 'viewport_0')">
<b>Show 3D</b>
</div>
</div>
<div id="show_0" class="collapse">
<div class="row">
<div class="col">
<div id="viewport_0" style="width:100%; height:800px;"></div>
</div>
</div>
</div>
</body>
</html>
It seems that "Show 3D" needs to be clicked twice for the 3D viewer to load. I would like it to load upon a single click.
I guess this function should be triggered only when the inside of the collapsible element has been fully loaded. I tried to tweak in this direction but I could not find a fix yet.

As it is a collapsible, just give some time to the collapsible to load. TO do that, you can wrap the entire script inside a set timeout like below
function showPDB(path,id) {
setTimeout(() => {
var stage = new NGL.Stage(id, {backgroundColor:'white'});
stage.loadFile(path).then(function (o) {
o.addRepresentation("cartoon", {color: 'white' });
o.autoView();
});
});
};

Related

Show a div on first page load only

I have a div that serves of container for a css animation that appears over the entire website's home page... a text and background that opens like curtains, revealing the website under it. It's like an intro landing page. The thing is I need it to appear only on first page load. I don't want it to appear on page refresh or if someone navigates thru the site and comes back to home page.
Can someone please show me how I would have to code this because I've search a lot on the web and didn't find any clear explanations for my particular case.
Here is the code for the div:
<div id="landContainer">
<div class="left-half" id="leftP"><article class="leftPanel"><img id="SloganLeft" src="Decouvrez.svg"></article></div>
<div class="right-half" id="RightP"><article class="rightPanel"><img id="SloganRight" src="Atteignez.svg"></article></div>
</div>
So the div I must display only on first page load would be the one with the ID landContainer, that contains a couple of other divs.
Since I'm new to this type of coding, I would need a complete example of the code I need to use with my div.
For Ian... here is the content of my index.html file...
<!DOCTYPE html>
<html>
<head>
<title>Landing page v2</title>
<link rel="stylesheet" type="text/css" href="landing.css" media="screen" />
</head>
<body>
<div id="landContainer">
<div class="left-half" id="leftP">
<article class="leftPanel"><img id="SloganLeft" src="Decouvrez.svg"></article>
</div>
<div class="right-half" id="RightP">
<article class="rightPanel"><img id="SloganRight" src="Atteignez.svg"></article>
</div>
</div>
<script type="text/javascript" src="scripts/snap.svg-min.js"></script>
<script scr="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
var isExists = localStorage.getItem("pageloadcount");
if (isExists != 'undefined') { $("#landContainer").hide();
}
localStorage.setItem("pageloadcount", "1");
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Landing page v2</title>
<link rel="stylesheet" type="text/css" href="landing.css" media="screen" />
<script type="text/javascript" src="scripts/snap.svg-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
if (localStorage.getItem("pageloadcount")) { $("#landContainer").hide();
}
localStorage.setItem("pageloadcount", "1");
});
</script>
</head>
<body>
<div id="landContainer">
<div class="left-half" id="leftP">
<article class="leftPanel"><img id="SloganLeft" src="Decouvrez.svg"></article>
</div>
<div class="right-half" id="RightP">
<article class="rightPanel"><img id="SloganRight" src="Atteignez.svg"></article>
</div>
</div>
</body>
</html>
The best way is to use session through which you can determine if its a new request or old.
Server side session will be best here
$( document ).ready(function() {
var isExists = localStorage.getItem("pageloadcount");
if (isExists != 'undefined') { $("#landContainer").hide();
}
localStorage.setItem("pageloadcount", "1");
});
<div id="landContainer">
<div class="left-half" id="leftP">
<article class="leftPanel"><img id="SloganLeft" src="Decouvrez.svg"></article>
</div>
<div class="right-half" id="RightP">
<article class="rightPanel"><img id="SloganRight" src="Atteignez.svg"></article>
</div>
</div>

How to reset a jQuery UI slider to null with multiple jQuery libraries

I am having trouble resetting jQuery UI sliders.
I get this error:
MyProject.OrderInfo.Search.js:187 Uncaught TypeError: $(...).slider is not a function
I think our problem has something to do with having multiple jQuery/Javascript libraries, stepping over each other, but I am uncertain. Everything my team has been trying has not worked. We simply need to reset our sliders to have NULL values. We need to use NULL, so that we know the user has not touched the slider. That way, we can exclude it from our API call parameters.
How can I reset the slider values to NULL?
Here is what the code looks like:
[OrderInfo.cshtml] (script area, top section):
<link rel="stylesheet" href="~/Content/order.css" />
<link rel="stylesheet" href="~/Content/bootstrap.css" />
<link rel="stylesheet" href="~/Content/backgrid-paginator.css" />
<link rel="stylesheet" href="~/Content/backgrid-filter.css" />
<link rel="stylesheet" href="~/Content/backgrid.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="~/Scripts/underscore.js"></script>
<script src="~/Scripts/jquery-2.2.0.js"></script>
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/backbone.js"></script>
<script src="~/Scripts/backbone.paginator.js"></script>
<script src="~/Scripts/backgrid.js"></script>
<script src="~/Scripts/backgrid-paginator.js"></script>
<script src="~/Scripts/backgrid-filter.js"></script>
<script src="~/Scripts/backgrid-select-filter.js"></script>
<script src="~/Scripts/MyProject.OrderInfo.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="~/Scripts/jquery.ui.touch-punch.js"></script>
[OrderInfo.cshtml] (body):
<div class="col-sm-7" id="divslider">
<div class="row filterHeader">
<div class="col-md-3 paddingZero">
<b>Tuition and Fees</b>
</div>
<div class="col-md-2 paddingZero">
<div class="input-group">
Min:
<span class="input-group-addon" id="MinOrderPrice"> </span>
</div>
</div>
<div class="col-md-5">
<div id="SliderOrderPrice"></div>
</div>
<div class="col-md-2 paddingZero">
<div class="input-group">
Max:
<span class="input-group-addon" id="MaxOrderPrice"> </span>
</div>
</div>
</div>
<!-- MORE HTML BODY CODE HERE, UI/search elements, DIVS, ETC ETC -->
<div class="row filterHeader">
<div class="col-md-3 paddingZero">
</div>
<div class="col-md-2 paddingZero">
</div>
<div class="col-md-4">
</div>
<div class="col-md-3 paddingZero">
<button class="btn btn-info" id="btnSearch" type="button">Search</button>
<button class="btn btn-primary" id="btnReset" type="button" style="min-width:71px">Reset</button>
</div>
</div>
</div>
<!-- END OF [OrderInfo.cshtml] BODY, ** NOTICE THE BOTTOM HAS A JS SCRIPT, EEEK!! ** -->
<script src="~/Scripts/MyProject.OrderInfo.Search.js"></script>
[MyProject.OrderInfo.Search.js] (a .JS file for searching Orders REST API):
//Declare slider variables as null and assign only in change function, to distinguish 'dirty' slider from a 'clean' slider
var minorderprice;
var maxorderprice;
//Tution and Fees slider
$("#SliderOrderPrice").slider({
range: true,
min: 0,
max: 50000,
values: [0, 50000],
step: 500,
slide: function (event, ui) {
$("#MinOrderPrice").html("$" + ui.values[0].toLocaleString());
if (ui.values[1] == 50000) {
$("#MaxOrderPrice").html("> $50,000")
}
else ($("#MaxOrderPrice").html("$" + ui.values[1].toLocaleString()))
},
change: function (event, ui) {
minorderprice = ui.values[0];
maxorderprice = ui.values[1];
}
});
$("#MinOrderPrice").html("$ 0");
$("#MaxOrderPrice").html("> $50,000");
$("#SliderOrderPrice").draggable(); //this is a hack to make the slider responsive on mobile devices (see touch-punch.js)
// Get the values of search checkboxes and sliders, after search button click
$("#btnSearch").click(function () {
//do a bunch of nifty things to produce a dynamic URL string, for REST API calls here. This works fine and is left out on purpose.
});
$("#btnReset").click(function () {
$('input:checkbox').removeAttr('checked'); //clear all checkboxes
$('#orderTerritory').prop('selectedIndex',0); //reset State/Territory dropdown to 'All States'
RenderJSGrid(); //re-draw grid
//how to reset slider values here?
$("#SliderOrderPrice").slider('values', 0, 50000); //this throws the error like the slider doesnt exist?
$("#SliderOrderPrice").slider('values', null, null); //would this work?
});
Notice there are references to:
<script src="~/Scripts/jquery-2.2.0.js"></script>
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
We have to do this because our BackgridJS implementation uses jQuery 2.2.
The sliders want to use 'jquery-ui.js', which I believe depends upon 'jquery-1.10.2.js'.
When the user clicks the Reset button, the error occurs and javascript acts like the slider isn't loaded. But it is, I can see it working in the UI. Could it be that the Reset button event needs to move somewhere else?
Any ideas? Help?
UPDATE #1:
I tried #Noctane's suggestion, but I still get the same error, no matter where I put the Reset function. I can put it inline, I can put it in other scripts but it just never works unfortunately.
Here is what I tried:
<link rel="stylesheet" href="~/Content/order.css" />
<link rel="stylesheet" href="~/Content/bootstrap.css" />
<link rel="stylesheet" href="~/Content/backgrid-paginator.css" />
<link rel="stylesheet" href="~/Content/backgrid-filter.css" />
<link rel="stylesheet" href="~/Content/backgrid.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="~/Scripts/underscore.js"></script>
<script src="~/Scripts/backbone.js"></script>
<script src="~/Scripts/backbone.paginator.js"></script>
<script src="~/Scripts/backgrid.js"></script>
<script src="~/Scripts/backgrid-paginator.js"></script>
<script src="~/Scripts/backgrid-filter.js"></script>
<script src="~/Scripts/backgrid-select-filter.js"></script>
<script src="~/Scripts/MyProject.OrderInfo.js"></script>
<script src="~/Scripts/jquery.ui.touch-punch.js"></script>
I have prepared a demo using jsFiddle, that uses jquery UI while utilizing both jquery v2.2.0 and jquery version 1.10.2, please have a look, you will see that as you move the slider it will set its changed value to the console, when you click reset it will set the slider to null.
See DEMO
You can achieve this with the following code:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" />
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<style>
#resetButton {
margin-top: 15px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
$( "#sliderTest" ).slider({
change: function( event, ui ) {
var s = ui.value;
console.log(s);
}
});
$("#resetButton").button({
icons: {
primary: "ui-icon-refresh"
}
});
$("#resetButton").click("click", function(event){
var s = $("#sliderTest").slider("value", null);
console.log(s);
});
</script>
<div id="sliderTest"></div>
<button id="resetButton">Reset</button>
You may need to re-arrange your includes in your application to get it to work. If you re-arrange the ones in the fiddle you will see the error you are getting, if you then switch them back to the way I have them arranged you will see it work.

Can't change bootstrap Tooltip title

I've already looked over several posts on stack overflow asking virtually the exact same question yet none of what I found on those questions has helped. I'm very new to JQuery and Bootstrap so maybe I'm just missing some really simple thing.
I want to be able to to change the title of the tooltip on different elements after the first initialization(ideally multiple times after initialization.) A simplified version of what I'm dealing with:
<canvas id="bag0" data-toggle="tooltip" title="test">
</canvas>
...
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
$(document).ready(function(){
$('#bag0').data('tooltip',false)
.tooltip({ title: 'new text'});
$('[data-toggle="tooltip"]').tooltip();
});
This method to change the title was given from posting: How to overwrite twitter bootstrap tooltip?
The tooltip always reads "test." I've tinkered with a few others things to no avail. I suspect I'm overlooking something obvious.
$(element).attr('title', 'NEW_TITLE').tooltip('fixTitle').tooltip('show');
Above code might help you.
$.tooltip(string) calls any function within the Tooltip class. And if you look at Tooltip.fixTitle, it fetches the data-original-title attribute and replaces the title value with it.
You can use the element id or class to make it more specific.
Help :)
Try this
$(element).tooltip().attr('data-original-title', "new title");
Source: github bootstrap issue
Bootstrap 4
$('#topic_1').tooltip('dispose').tooltip({title: 'Goodbye'}).tooltip('show')
$('#topic_1').tooltip({title: 'Hello'}).tooltip('show');
setTimeout( function() {
$('#topic_1').tooltip('dispose').tooltip({title: 'Goodbye'}).tooltip('show');
}, 5000);
#topic_1 {
border: 1px solid red;
margin: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<div id="topic_1">Topic 1</div>
Change Bootstrap 4 Tooltip title
$(document).ready(function() {
// initilizing Tooltip
$('[data-toggle="tooltip"]').tooltip();
// Get the Tooltip
let btn_tooltip = $('#my-btn');
// Change Tooltip Text on mouse enter
btn_tooltip.mouseenter(function () {
btn_tooltip.attr('title', 'Default Tooltip').tooltip('dispose');
btn_tooltip.tooltip('show');
});
// Update Tooltip Text on click
btn_tooltip.click(function () {
btn_tooltip.attr('title', 'Modified Tooltip').tooltip('dispose');
btn_tooltip.tooltip('show');
});
});
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<p>Click the button:</p>
<button id="my-btn" type="button" class="btn btn-primary" data-toggle="tooltip" title="Default tooltip">Click Me</button>
</div>
</body>
</html>
This might help
$('[data-toggle="tooltip"]').attr("title","NEW TEXT");
If you want to for a particular element, say a <div>
$('div[data-toggle="tooltip"]').attr("title","NEW TEXT");
Try following,
$(document).ready(function(){
$('#bag0').attr('title', 'new text')
.tooltip('destroy') // if you are using BS4 use .tooltip('dispose')
.tooltip({ title: 'new text'});
$('[data-toggle="tooltip"]').tooltip('show');
});
<canvas id="bag0" data-toggle="tooltip" title="test">
</canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
I have a solution for similiar case. I change the title in tooltip dynamicaly with ajax.
first just enable the tooltips:
$('[data-toggle="tooltip"]').tooltip()
Then change the title attribute, then re init the tooltip
$("#foo").attr('title','TheNewTitle');
$('[data-toggle="tooltip"]').tooltip('dispose');
$('[data-toggle="tooltip"]').tooltip()
I may be a bit too late but my solution to this was to change the data-original-title
$('.sample').attr('data-original-title': 'new title');
This changes the bootstrap tool tip title automatically.

click event not happening with bootstrap panel

I'm trying to make my own class with panels that open and close content using Bootstrap and jQuery (not an accordion, I want multiple open at a time). However, the click event isn't working for me and I have no idea why... I tried the "*" selector and the alert was working but it's not working when I try to associate it with specific elements.
Practice2.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Practice 2</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 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>
<link rel="stylesheet" href="../static/css/prism.css">
<link rel="stylesheet" href="../static/css/styles.css">
<script src="../static/js/prism.js"></script>
<script src="../static/js/script.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="panel panel-default panel-toggle" id="demo">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code><br>
Explanation
</div>
</div>
</div>
</body>
</html>
script.js
// $(".panel-toggle:panel-header").click(function(){
// // $(this).next().toggle();
// alert("hello");
// });
$("#demo").click(function(){
alert("hello");
});
styles.css
.panel-toggle .panel-heading:after {
font-family:'Glyphicons Halflings';
content:"\e114";
float: right;
color: grey;
}
.panel-toggle .collapsed:after {
content:"\e080";
}
.panel-toggle .panel-body {
}
Clearly the rest of the code needs some adjustment but I'm just troubleshooting this part right now and would appreciate some advice on what I'm missing. Thanks!
With
HTML
<div class="panel panel-default panel-toggle">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code>
Explanation
</div>
</div>
JS
$(document).ready(function(){
$(".panel-heading").click(function(){
$(this).next().toggle("slow");
});
});
works
JSFiddle demo
You should put your jQuery code in document.ready block ensure your code working after those element been generated.
Script.js should be changed like this.
$(document).ready(function(){
$("#demo").click(function(){
alert("hello");
});
});

Foundation Accordion not loading if not declared in HTML

I am fairly new to JS and i thought i understood the order in which the components of the page are loaded but this puzzles me.
I'm working with foundation 5 and i am using an accordion component. In my js script i load data and put it into an accordion which then becomes the inner html of the mainContainer div.
<link rel="stylesheet" href="css/foundation.complete.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/myCss.css" />
<script src="js/vendor/modernizr.js"></script>
<script src="js/app.js"></script>
<script src="js/vendor/jquery.js"></script>
<body onload="iniciarPg()">
<div id="principal" class="mainContainer">
<dl class="accordion" data-accordion > </dl>
</div>
function iniciarPg()
{
$(document).foundation({
accordion: { toggleable: true }
});
loadData();
}
</script>
<!--SCRIPTS -->
<script src="js/classie.js"></script>
<script src="js/foundation.min.js"/>
<script src="js/foundation/foundation.accordion.js"/>
</body>
The part i cannot comprehend is that although all the inner HTML of the mainContainer gets replaced, if i delete <dl class="accordion" data-accordion > </dl> from my html, then when the JS loads, the page does no display the accordeon correctly, it does not expand when clicked.
You need to reflow your foundation plugin as the data comes later through ajax.
function iniciarPg()
{
$(document).foundation({
accordion: { toggleable: true }
});
loadData();
//make sure the ajax has been finished and the HTML is properly set, otherwise move following line to you ajax success handler end.
$(document).foundation('reflow');
}
</script>

Categories

Resources