Why emitted events of livewire is not triggered? - javascript

In laravel 7 learning livewire/livewire 1.3 I encountered that emitted
events are not always triggered
I created component with command
php artisan make:livewire hostel/hostelsHomepageSpotlight
and simplifying the code I do not see alert of event.
In app/Http/Livewire/Hostel/HostelsHomepageSpotlight.php :
<?php
namespace App\Http\Livewire\Hostel;
use Auth;
use DB;
use App\Config;
use App\Hostel;
use App\HostelImage;
use App\library\CheckValueType;
use App\Settings;
use Livewire\Component;
class HostelsHomepageSpotlight extends Component
{
public function render()
{
$hostels = [];
$current_page= 1;
$hostel_rows_count = Hostel
::getByStatus('A')
->count();
$this->emit('hostelsHomepageSpotlightOpened', [ 'mode'=> 'hostels_homepage_spotlight', 'current_page'=>$current_page, 'hostel_rows_count'=>$hostel_rows_count ] ); // EMIT EVENT
return view('livewire.hostel.hostels-homepage-spotlight', [
'hostelsDataRows' => $hostels,
'hostel_rows_count'=> $hostel_rows_count,
'current_page'=> $current_page,
]);
}
}
and in resources/views/livewire/hostel/hostels-homepage-spotlight.blade.php:
<div>
<h1>hostelsHomepageSpotlightOpened</h1>
</div>
<script>
// If to uncomment line below I see alert
// alert( 'resources/views/livewire/hostel/hostels-homepage-spotlight.blade.php::' )
window.livewire.on('hostelsHomepageSpotlightOpened', data => {
// I DO NOT SEE ALERT BELOW ANYWAY
alert( 'hostelsHomepageSpotlightOpened::' )
console.log('facility_opened data::')
console.log(data)
// alertsInit(data.mode)
// lazyImagesInit("img.lazy_image")
})
</script>
Why event is not triggered ? Is there is a way to debug it ?
UPDATED # 2:
I know the rule about wrapping div(without any class or styles definitions).
Have I also to remove JS code ?
I tried to move all JS code in resources/js/app.js :
window.$ = window.jQuery = require('jquery');
require('./bootstrap');
var Turbolinks = require("turbolinks")
Turbolinks.start()
// If to uncomment the line below I see it
// alert( '::resources/js/app.js' )
window.livewire.on('hostelsHomepageSpotlightOpened', data => {
// I do not see this alert
alert( 'hostelsHomepageSpotlightOpened::' )
console.log('facility_opened data::')
console.log(data)
// alertsInit(data.mode)
// lazyImagesInit("img.lazy_image")
})
and in my resources/views/layouts/app.blade.php :
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" xmlns:livewire="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel:Livewire</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet" type="text/css">
<link rel="icon" type="image/png" href="/favicon.ico"/>
<link href="/css/app.css" rel="stylesheet">
<script src="{{ asset('js/lazyload.js') }}"></script>
<!-- Styles -->
#livewireStyles
#livewireScripts
<script src="{{ asset('/js/app.js') }}"></script>
<script src="{{ asset('/js/app/app_funcs.js') }}"></script>
</head>
<body class="text-center">
<div class="flexbox-parent page_container " id="page_content">
<header class="flexbox-item header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
...
</nav>
</header>
<main class="flexbox-item fill-area content flexbox-item-grow">
#yield('content')
</main>
<footer class="flexbox-item footer ml-3 mr-3">
...
<p class="m-2">copyright_text</p>
</footer>
</div>
</body>
</html>
And my code is nit triggered anywat!
I suppose that is valid structure of my app as app.js AFTER #livewireStyles
and #livewireScripts
UPDATED # 3:
I tried and that does not work. I have login form :
<article class="page_content_container">
...
<form class="form-login" wire:submit.prevent="submit">
<input
wire:model.lazy="form.email"
name="email"
id="email"
class="form-control editable_field"
placeholder="Your email address"
autocomplete=off
>
</form>
...
</article> <!-- page_content_container -->
{{--#push('scripts')--}}
<script>
$("#email").focus();
</script>
{{--#endpush--}}
When #push/#endpush are commented as on lines above it works ok and focus is set to email input.
But if to uncomment these 2 lines focus is not set.
I modified my resources/views/layouts/app.blade.php :
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel:Livewire</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet" type="text/css">
<link rel="icon" type="image/png" href="/favicon.ico"/>
<link href="/css/app.css" rel="stylesheet">
<!-- Styles -->
#livewireStyles
<script src="{{ asset('/js/app.js') }}"></script>
<script src="{{ asset('js/lazyload.js') }}"></script>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine#v2.x.x/dist/alpine.min.js" defer></script>
#livewireScripts
#stack('scripts')
<script src="{{ asset('/js/app/app_funcs.js') }}"></script>
app.js - is first as bootstrap and jquery are included there...
Thanks!

Livewire expects components wrapped by a div element.
Sample:
< div>
Your content...
</ div>
What I am saying is that I am not sure you can include javascript in your Livewire blade. Try by moving it out to your app.js file and see if it works because the rest looks good.
I remember having trouble just because the blade’s first line was a html comment, instead of 🙈
So, always, first line of your livewire blade must be < div>, and last line </ div>
Hope that helps!

If you want to write script under livewire blade try this way. in your master layout put under #livewireScripts
#stack('scripts')
Now you can push scripts in this stack from your livewire blade file like this:
#push('scripts')
<script>
// some js code
</script>
#endpush

UPDATED: It makes sense why in your case it does NOT work. You should NOT emit the event in the RENDER function IFF you want to listen for it in the same view that is about to be rendered. In simple words for your case, the emit happens before the view loads, thus, by the moment your view is ready, it will be a 'bit' late to listen to it, you lost it! :-)
Solution: put the JS (the window.livewire.on... ) one step outside so it will be already ready by the moment you emit the event in the render.
In simple words, place the JS code in the scripts section of the parent file, the file you include the following
#livewire('hostel.hostels-homepage-spotlight')
P.S. When you are dealing with livewire, to listen for an event or fire one,
do not forget to wrap it in the document ready, i.e.,
$( document ).ready(function() {
livewire.emit('event_foo', 'foooo');
});
Thus, your spotlight PARENT page should look something like this:
<script>
$( document ).ready(function() {
window.livewire.on('hostelsHomepageSpotlightOpened', data => {
alert( 'hostelsHomepageSpotlightOpened::' )
console.log('facility_opened data::')
console.log(data)
});
});
</script>
Cheers,

Related

Running JavaScript libraries (Looper) in Blazor Server-side - some javascript code is not running

I am trying to implement Looper theme to my blazor server-side app, and I have the javascript libraries referenced at the end of the in _Host.cshtml.However some scripts in theme.min.js is not running. Why?
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script src="_framework/blazor.server.js"></script>
My problem is that while
<div data-toggle="drowndown"></div> works, but hamburger menu toggle
<button class="hamburger hamburger-squeeze mr-2" type="button" data-toggle="aside-menu" aria-label="toggle aside menu"><span class="hamburger-box"><span class="hamburger-inner"></span></span></button>
does not work. What am I missing here? What am I doing wrong? My theme change script also isn't running. If I step through theme.js and I can see that this script runs when blazor is not active (commenting out blazor.js) but with blazor active, this script does not run.
(line 610) in /library/javascript/theme.js
}, {
key: "toggleAside",
value: function toggleAside() {
var _this4 = this;
var $trigger = $('[data-toggle="aside"]');
$trigger.on('click', function () {
var isShown = $('.app-aside').hasClass('show');
$trigger.toggleClass('active', !isShown);
if (isShown) _this4.hideAside();else _this4.showAside();
});
}
My educated guess is that theme.js is using something that blazor does not allow? Is anybody experienced enough with Looper theme (or with javascript in general) to know why it wouldn't work? Particularly the hamburger toggle and the theme switching code
(line 1992 in /library/javascript/theme.js)
var Looper = function () {
var Looper = new Theme(); // toggle skin thought button
$('[data-toggle="skin"]').on('click', function (e) {
e.preventDefault();
var skin = Looper.skin === 'dark' ? 'default' : 'dark';
Looper.setSkin(skin); // we need to refresh our page after change the skin
location.reload();
}).each(function () {
var isDarkSkin = Looper.skin === 'dark';
var $icon = $(this).find('.fa-moon');
if (isDarkSkin) {
$icon.addClass('far');
$icon.removeClass('fas');
}
}); // make it global
return Looper;
}();
This is the website https://worshipground.azurewebsites.net/ You can use the inspector tool to see that blazor has been correctly loaded and all the javascript files are loaded in /library/javascript and /library/vendor/...
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- End Required meta tags -->
<title> Starter Template | Looper - Bootstrap 4 Admin Theme </title>
<base href="~/" />
<meta name="theme-color" content="#3063A0">
<link rel="apple-touch-icon" sizes="144x144" href="Library/apple-touch-icon.png">
<link rel="shortcut icon" href="Library/favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans:400,500,600" rel="stylesheet">
<link rel="stylesheet" href="/Library/vendor/open-iconic/font/css/open-iconic-bootstrap.min.css">
<link rel="stylesheet" href="/Library/vendor/fontawesome/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="/Library/stylesheets/theme.min.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/theme-dark.min.css" data-skin="dark">
<link rel="stylesheet" href="/Library/stylesheets/custom-app.css">
<link rel="stylesheet" href="/Library/stylesheets/custom.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/custom-dark.css" data-skin="dark">
<script>
var skin = localStorage.getItem('skin') || 'default';
var isCompact = JSON.parse(localStorage.getItem('hasCompactMenu'));
var disabledSkinStylesheet = document.querySelector('link[data-skin]:not([data-skin="' + skin + '"])');
// Disable unused skin immediately
disabledSkinStylesheet.setAttribute('rel', '');
disabledSkinStylesheet.setAttribute('disabled', true);
// add flag class to html immediately
if (isCompact == true) document.querySelector('html').classList.add('preparing-compact-menu');
</script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
You may find you have your work cut out in terms of making a JavaScript heavy template work nicely in Blazor.
You will probably need to utilise IJSRuntime
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-5.0
I think I know where this problem comes from! If you comment out the following code on the "Host.cshtml" file, this problem will most likely go away!
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
But!!!! You will get some javascript errors related to "WebSocket" instead! something like this:
"WebSocket is not in the OPEN state"
Or
"Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State."
The cause of these errors is a conflict between "pace.min.js" file and "blazor.server.js" file! You can check this link for more information and get more help

Kendo UI for ASP.NET Core - kendo is not defined

I keep getting the following error when I try to create a Grid or a Chart using Kendo UI. A simple ComboBox will work, though. We are using the commercial lisence and downloaded the js and css from Telerik's website while authenticated.
Uncaught ReferenceError: kendo is not defined
Uncaught ReferenceError: $ is not defined
Config: _Layout.cshtml
<head>
<environment names="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/lib/kendo-ui/styles/kendo.common-bootstrap.min.css" />
<link rel="stylesheet" href="~/lib/kendo-ui/styles/kendo.bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet"
href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.common-bootstrap.min.css"
asp-fallback-href="~/lib/kendo-ui/styles/kendo.common-bootstrap.min.css"
asp-fallback-test-class="k-common-test-class"
asp-fallback-test-property="opacity" asp-fallback-test-value="0" />
<link rel="stylesheet"
href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.bootstrap.min.css"
asp-fallback-href="~/lib/kendo-ui/styles/kendo.bootstrap.min.css"
asp-fallback-test-class="k-theme-test-class"
asp-fallback-test-property="opacity" asp-fallback-test-value="0" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
</head>
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/lib/kendo-ui/js/kendo.all.min.js"></script>
<script src="~/lib/kendo-ui/js/kendo.aspnetmvc.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="https://kendo.cdn.telerik.com/2017.2.504/js/kendo.all.min.js"
asp-fallback-src="~/lib/kendo-ui/js/kendo.all.min.js"
asp-fallback-test="window.kendo">
</script>
<script src="https://kendo.cdn.telerik.com/2017.2.504/js/kendo.aspnetmvc.min.js"
asp-fallback-src="~/lib/kendo-ui/js/kendo.aspnetmvc.min.js"
asp-fallback-test="kendo.data.transports['aspnetmvc-ajax']">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
_ViewImports.cshtml
#using Microsoft.AspNetCore.Identity
#using Kendo.Mvc.UI
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
View.cshtml
<div class="invoice-charts-container">
<h3>Invoice History Week Totals</h3>
<div class="demo-section k-content wide">
#(Html.Kendo().Chart()
.Name("chart")
.HtmlAttributes(new { style = "height: 400px;" })
.Title("Site Visitors Stats /thousands/")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.SeriesDefaults(seriesDefaults => seriesDefaults
.Column().Stack(true)
)
.Series(series =>
{
series.Column(new double[] { 56000, 63000, 74000, 91000, 117000, 138000 }).Name("Total Visits");
series.Column(new double[] { 52000, 34000, 23000, 48000, 67000, 83000 }).Name("Unique visitors");
})
.CategoryAxis(axis => axis
.Categories("Jan", "Feb", "Mar", "Apr", "May", "Jun")
.MajorGridLines(lines => lines.Visible(false))
)
.ValueAxis(axis => axis
.Numeric()
.Line(line => line.Visible(false))
)
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}")
)
)
</div>
<div class="box wide">
<div class="box-col">
<h4>API Functions</h4>
<ul class="options">
<li>
<input id="typeColumn" name="seriesType"
type="radio" value="column" checked="checked" autocomplete="off" />
<label for="typeColumn">Columns</label>
</li>
<li>
<input id="typeBar" name="seriesType"
type="radio" value="bar" autocomplete="off" />
<label for="typeBar">Bars</label>
</li>
<li>
<input id="typeLine" name="seriesType"
type="radio" value="line" autocomplete="off" />
<label for="typeLine">Lines</label>
</li>
<li>
<input id="stack" type="checkbox" autocomplete="off" checked="checked" />
<label for="stack">Stacked</label>
</li>
</ul>
<p>
<strong>refresh()</strong> will be called on each configuration change
</p>
</div>
</div>
<script>
$(document).ready(function() {
$(".options").bind("change", refresh);
$(document).bind("kendo:skinChange", updateTheme);
});
function refresh() {
var chart = $("#chart").data("kendoChart"),
series = chart.options.series,
type = $("input[name=seriesType]:checked").val(),
stack = $("#stack").prop("checked");
for (var i = 0, length = series.length; i < length; i++) {
series[i].stack = stack;
series[i].type = type;
};
chart.refresh();
}
function updateTheme() {
$("#chart").getKendoChart().setOptions({ theme: kendoTheme });
}
</script>
</div>
Here is where the error occurs in the DOM:`
Uncaught ReferenceError: kendo is not defined
<script>kendo.syncReady(function(){jQuery("#chart").kendoChart(
Uncaught ReferenceError: $ is not defined
<script>
$(document).ready
(function() {
$(".options").bind("change", refresh);
$(document).bind("kendo:skinChange", updateTheme);
});
EDIT - It seems the javascript files are loaded but the errors are happening anyway:
When I had this problem, after upgrading an existing project to 2017.2.504, it was because I had my scripts defined in the body... Like you.
They have to be in the head. Here's the response I got from support:
kendo.syncReady was introduced to address a major issue with jQuery 3.1.1 and the way Kendo UI widgets are generated on the client when using the MVC wrappers. This change, however, requires that Kendo UI script files are referenced in the page head section (this has been the default instruction for Kendo UI references in the past, as well). Please, try moving your Kendo UI references to the tag, after the jQuery files are referenced and let me know if the error keeps occurring.
Adding to what #Brian MacKay already mentioned, you have the possibility to defer script output:
#(Html.Kendo().DatePicker().Name("datepicker").Deferred())
When you're using .Deferred(), you'll store the rendered JavaScript and you'll have the possibility to place this deferred script wherever you want:
<head>
</head>
<body>
<!-- stuff -->
#(Html.Kendo().DatePicker().Name("datepicker").Deferred(true))
<!-- other stuff -->
<script src="https://kendo.cdn.telerik.com/2017.1.223/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.1.223/js/kendo.web.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.1.223/js/kendo.aspnetmvc.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.1.223/js/kendo.all.min.js"></script>
#Html.Kendo().DeferredScripts()
</body>
If you're on a development box, prefix all src and href attributes that start with https:// to use //:. Chances are high that your development environment is not using SSL, so it can't use any resources over SSL links (javascript won't load at all!). The prefix change will make the urls inherit whatever the page is using.
See more here

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");
});
});

How to reference a React class from generic javascript

I have this index.html :
<html>
<head>
<title>Sample App</title>
<link href="./src/css/bootstrap.min.css" rel="stylesheet" />
<link href="./src/css/bootstrap.dashboard.css" rel="stylesheet">
</head>
<body>
<div id='root'>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="./src/js/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:26665/signalr/hubs"></script>
<script type="text/javascript" src="/static/bundle.js"></script>
<script type="text/javascript">
$(function() {
var myHub = $.connection.signalRTwitchBotParserHub;
myHub.client.OnNewMessage = function (data) {
// Call AppActions.dispatchMessage(message);
};
$.connection.hub.url = "http://localhost:26665/signalr";
$.connection.hub.start()
});
</script>
</body>
How can I call a React-created class from there? I would like to replace the // Call AppActions.dispatchMessage(message);
You could do something like the following. What that does is create an instance of YourReactClass that renders itself as a child of your div with the id of root. It also passes the message as a property into the react instance so that it can make use of that data. Note that I added key="rootclass" to ensure that every time this code is called, React continues to reuse the DOM nodes created by the react class instead of removing the old nodes and adding new ones.
React.render((<YourReactClass key="rootclass" message={message} />), document.getElementById('root'));
You can include React onto the page by adding
<script src="https://fb.me/react-0.13.3.min.js"></script>
See the full list of downloads for other includable options (such as the JSX Transformer).

how to load an external html file that contains scripts

Unfortunately, I am not sure to understand anything to java, jquery and all this kind of thing. Nevertheless, I am trying to get some inspiration on forums in order to make a personal website that contains a vertical navbar and a div container in which external html pages will be loaded. Each html file uses an html5 applet called JSmol, which plots 3D molecules that can be manipulated interactively. The main page looks like this:
<!DOCTYPE html>
<html>
<head>
<title> 3D Chemistry </title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="Chem3D-CSS/MolChem.css" />
<link href='http://fonts.googleapis.com/css?family=Archivo+Narrow' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<!-- META TAGS start -->
<meta name="Title" content="Molecular Chemistry" />
<meta charset="UTF-8">
<!-- META TAGS end -->
<script type="text/javascript">
$(document).ready(function() {
// select all the links with class="lnk", when one of them is clicked, get its "href" value
// load the content from that URL and check the "status" of the request
// place the response or an error message into the tag with id="content"
$('a.lnk').click(function() {
var url = $(this).attr('href');
$('#content').load(url, function(response, status, xhr) {
// check the status, if "success", place the response into #content
// else, if "error", define an error message and insert it into #content
// else, display an Alert with the status
if(status=='success') {
$('#content').html(response);
}
else if(status=='error') {
var ermsg = '<i>There was an error: '+ xhr.status+ ' '+ xhr.statusText+ '</i>';
$('#content').html(ermsg);
}
else { alert(status); }
});
return false;
})
});
</script>
</head>
<body class="s_page" alink="#ee0000" link="#0000ee" vlink="#551a8b">
<div id="header"> <a id="UPS-link" href="http://www.univ-tlse3.fr/" title="Paul Sabatier University - Toulouse III">
<img src="Chem3D-IMAGES/UT3_PRES_logoQ.png" alt="Paul Sabatier University" id="logoUPS" width=300px />
</a>
</div>
<div id="vmenu">
<ul>
<li>Home</li>
<li>3D Molecules
<ul>
<li>Mol1</li>
<li>Mol2</li>
</ul>
</li>
<li>Symmetry
<ul>
<li>Symmetry Elements
<ul>
<li>C<sub>2</sub>H<sub>6</sub></li>
<li>Ru<sub>4</sub>H<sub>4</sub>(CO)<sub>12</sub></li>
</ul>
</li>
<li>Point Groups
</li>
</ul>
</li>
<li>Solids
<ul>
<li>fcc</li>
<li>hcp</li>
</ul>
</li>
</ul>
</div>
<div id="content">
</div>
<div class="s_author" id="footer">
author: romuald.poteau_at_univ-tlse3.fr
<br/>last modification: 2013/12/16
</div>
</body>
</html>
Up to now, I have worked on the PG.html file (Point Group entry in the vertical menu), which works perfectly fine when it is loaded separately. But is not the case when it is loaded inside the main page as an external html page. The title is the only thing that appears, it seems that the jsmol application is not properly initialized. May be this is specific to the invocation of jsmol ; or is this a general issue when one wants to load hmtl files with embedded scripts ?
<!DOCTYPE html>
<html>
<head>
<title> POINT GROUPS </title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="Chem3D-CSS/MolChem.css" />
<!-- META TAGS start -->
<meta name="Title" content="Molecular Chemistry" />
<meta name="Format" content="text/html" />
<meta name="Language" content="en" />
<meta charset="UTF-8">
<!-- META TAGS end -->
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="./JSmol.min.js"></script>
<script type="text/javascript">
// ---------------------------------------------------------------------------------
////// every page will need one variable and one Info object for each applet object
var Info = {
width: 500,
height: 500,
color: "0xC0C0C0",
use: "HTML5",
jarPath: "java",
j2sPath: "j2s",
jarFile: "JmolApplet.jar",
isSigned: false,
addSelectionOptions: false,
serverURL: "php/jsmol.php",
readyFunction: jmol_isReady,
console: "jmol_infodiv",
disableInitialConsole: true,
debug: false,
}
</script>
</head>
<body class="s_page" alink="#ee0000" link="#0000ee" vlink="#551a8b">
<div class="s_title" id="titlePG">
Point Groups
</div>
<div class="s_normal" id="mainPG">
<table border="0">
<tbody>
<tr valign="top">
<td nowrap="nowrap">
<script type="text/javascript">
Jmol.getApplet("Jmol1", Info);
Jmol.script(Jmol1,'load Chem3D-data/nh2cl.xyz;');
Jmol.resizeApplet(Jmol1, 500);
</script>
<br>
</td>
<td>
<script>
Jmol.setButtonCss(null,"style='width:300px'")
Jmol.jmolButton(Jmol1,"load Chem3D-data/nh2cl.xyz;", "NH2Cl (Cs)");
Jmol.jmolBr();
Jmol.jmolButton(Jmol1,"load Chem3D-data/cis-dichloroethylene.xyz;", "cis-dichloroethylene (C2v)");
Jmol.jmolBr();
Jmol.jmolButton(Jmol1,"load Chem3D-data/trans-dichloroethylene.xyz;", "trans-dichloroethylene (C2h)");
</script>
<br>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
I have tried to find an answer to this question by checking previous posts, but my poor skills do not allow me to identify relevant suggestions for such issue.
Thanks for any help.
// Create a DOM object from a URL
$html = file_get_html('http://www.google.com/');
// Create a DOM object from a HTML file
$html = file_get_html('test.htm');

Categories

Resources