Where to put JS file in Rails? - ruby-on-rails

I want to know where to put javascript file in ruby on rails.
I am using jQuery dialogue box in my app. All jQuery and CSS files I put under assets/javascripts and assets/stylesheets.
Now I have some JavaScript code in my view page that is "my_event". Where to put this JavaScript code?
I googled for this and found something that suggested to make a my_event.js file and put this file inside the views/useraccount directory.
Seeking your valuable suggestion.
Controller useraccount.rb
View my_event.html.erb
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header : {
left : 'prev,next today',
center : 'title',
right : 'month,agendaWeek,agendaDay'
},
// US Holidays
events : '/useraccount/my_event',
eventClick : function(event) {
// alert (JSON.stringify(event,null,4)); return false;
if (event.description) {
var a = '<button onclick="addToMycal(' + event.id + ')">UnJoin</button>'
$("#Successmes").empty();
$('#event-desc').html(event.description);
$('#add-to-my-cal').html(a)
$("#dialog-modal").dialog({
height : 350,
width : 600,
modal : true,
buttons : {
Ok : function() {
$(this).dialog("close");
}
}
});
} else {
$('#event-desc').html("<h4>Oops!</h4> No Data Available");
$("#dialog-modal").dialog({
height : 300,
width : 363,
modal : true,
buttons : {
Ok : function() {
$(this).dialog("close");
}
}
// alert (event.description);
});
}
},
});
});
</script>
<script>
function addToMycal(val) {
$.getJSON("/useraccount/delete_event?d=" + val, function(data) {
// alert (JSON.stringify(data,null,4)); return false;
$("#Successmes").empty();
$("#event-desc").html(data.msg)
$("#add-to-my-cal").remove();
});
}
</script>
<style>
#calendarbody {
margin-top: 40px;
text-align: center;
font-size: 14px;
font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
}
#calendar {
width: 900px;
margin: 0 auto;
background-color: #E7EAF6;
}
</style>
<div id="calendarbody">
<div id='calendar'></div>
</div>
<div id="dialog-modal" title=" Event Description">
<p id="event-desc"></p>
<div id="add-to-my-cal"></div>
<p id="Successmes"></p>
</div>

Keep it in assets/javascripts folder and cross check for if you have written "require_tree ." That's it.
This will be available on every page...

Put it in assets/javascripts folder, and require it in your application.js file. If your application.js file has require_tree ., no need to require your js file again.

Related

How to take screenshot using electronjs?

I'm building a cross-platform desktop application. I'm using electronjs framework for my desktop app development.And I want to add a functionality of taking screenshot every 5 minutes when my app starts!
help will be appreciated
my main.js
// Modules to control application life and create native browser window
const {app, BrowserWindow,Tray,Menu} = require('electron')
const path = require('path')
const iconz = path.join(__dirname,'/img/download.png')
const fs = require('fs')
var config = require('./login.json');
const shell = require('electron').shell
let tray = null
function createWindow () {
tray = new Tray(iconz)
const contextMenu = Menu.buildFromTemplate([
{ label: 'User:'+ config.username, type: 'radio',enabled:false},
{type:'separator'},
{ label: 'Show DeskTime', type: 'radio',
click() {
shell.openExternal('http://coinmarketcap.com')
}
},
{type:'separator'},
{ label: 'Private Time', type: 'radio',
click() {
checked:true
}
},
{type:'separator'},
{ label: 'LogOut', type: 'radio' },
{type:'separator'},
{ label: 'Quit', type: 'radio',
click() {
app.quit()
}
}
])
tray.setToolTip('This is my application.')
tray.setContextMenu(contextMenu)
console.log(config.username + ' ' + config.password);
if(config.username == ""){
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
}
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
my index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1;}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.imgcontainer {
text-align: center;
margin: 12px 0 6px 0;
}
img.avatar {
width: 20%;
border-radius: 40%;
}
.container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
/* Change styles for span and cancel button on extra small screens */
#media screen and (max-width: 300px) {
span.psw {
display: block;
float: none;
}
.cancelbtn {
width: 100%;
}
}
</style>
</head>
<body>
<h2>Login Form</h2>
<form action="/action_page.php" method="post">
<div class="imgcontainer">
<img src="login_logo.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<span class="psw">Forgot password?</span>
</div>
</form>
<label id="screenshot-path">Path:</label>
<button id="screen-shot" type="button" class="cancelbtn">Singup</button>
</body>
<script src="./renderer.js"></script>
</html>
My codes are given above, please go through this and help me to take screenshot on a certain interval.And also how to save in screen shots in predefined folder.
You can use contents.capturePage([rect]) on your main process. if you omits rect args it will capture the whole window. This will return a promise with native image .
To capture it on every 5 minute, you can set a setInterval(<function>,<time in millis>)
To save on specific folder you can use path module
ex:
const path = require('path')
const myFolderPath = path.join(__dirname, "myfolderinsideProject")
fs.writeFile(path.join(myFolderPath,`test${count}.png`), ....)
example code to save Captured window on current project folder:
// Modules to control application life and create native browser window
const {app, BrowserWindow } = require('electron')
const path = require('path')
const fs = require('fs')
let mainWindow, count=0;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
//starting when the app is ready
app.on('ready', () => {
//setting the time interval for 3 second (3000 in millis)
setInterval(()=>{
console.log(`Capturing Count: ${count}`)
//start capturing the window
mainWindow.webContents.capturePage().then(image =>
{
//writing image to the disk
fs.writeFile(`test${count}.png`, image.toPNG(), (err) => {
if (err) throw err
console.log('Image Saved')
count++
})
})
}, 3000); //tome in millis
});
or you can use this npm package on renderer process

run 2nd jquery animation with the end of 1st animation

I created a simple js banner.
First a company name will run into the center from left and then fading in an image logo
html
<div id="banner-container">
<div id="companyname"><p>P.Classique Trading Co. Ltd.</p></div>
<div id="logo"><img src="img/twitter_logo.png" width="100" height="100" /></div>
</div>
css
#banner-container {
position:relative;
left:300px;
top:100px;
overflow: hidden;
display:box;
background-color: #282800;
width:500px;
height:300px;
color:#FFFFFF;
}
#companyname {
position: relative;
color:yellow;
top:15px;
left:-500px;
font-family: 'Finger Paint', cursive;
}
#logo {
position: relative;
display:none;
top:50px;
left:200px;
}
js
$(document).ready(function() {
var left = $('#companyname').offset().left;
$("#companyname").css({left:left}).animate({"left":"120px"}, {duration:1000, easing:'easeOutBounce'});
$("#logo").fadeIn(1500);
}
);
the result is two animations start at the same time which is not I want to.
Working jsFiddle Demo
Use a callback for your animation:
$("#companyname")
.css({left:left})
.animate(
{"left":"120px"},
{
duration:1000,
easing:'easeOutBounce',
complete: function () {
$("#logo").fadeIn(1500);
}
}
);
Try this fiddle: http://jsfiddle.net/KhsWt/
You can use the second fadein as parameter for when first one finishes
$(document).ready(function() {
var left = $('#companyname').offset().left;
$("#companyname").css({left:left}).animate({left:"120px"}, 1000, 'easeOutBounce',
function() {
$("#logo").fadeIn(1500);
}
)});

jquery customizing dialog buttons

I am using jquery dialog with query ui 1.8.7.custom.min.js
I need to customize the buttons on the the dialog and the location where they show up on the dialog. I was able for the most part to customize my dialog box but customizing buttons and its location had been tough cookie so far.
Please find screen shots and code below
HTML:
<style>
.ui-dialog, .ui-dialog-content {
border:1px solid #cde68c;
border-bottom:0px;
background-color: white !important;
color: #333;
font: 12px/180% Arial, Helvetica, sans-serif;
}
.ui-dialog-titlebar {
display:none;
}
#ui-dialog-title-dialog {
color: yellow !important;
text-shadow: none;
}
.ui-dialog-buttonpane {
border:1px solid #cde68c;
border-top:0px;
margin-bottom: 1%;
}
</style>
<div id="dialog">
<p><span id="emailNotice"></span></p>
</div>
Javascript:
$j(document).ready(function() {
$j('#dialog').dialog('open');
$j('#emailNotice').html('show some notice text abcd');
$j('#dialog').dialog({
modal:true,
autoOpen: false,
width: 600,
buttons: {
"Ok": function() {
$j(this).dialog("close");
},
"Cancel": function() {
className: 'cancelButtonClass',
$j(this).dialog("close");
}
}
});
});
I want to be able to position buttons left , right , top / bottom etc
You can always pass an empty object for the buttons property. You would then add your buttons directly in your "dialog" div. Of course, this would mean you'd have to handle the button click events manually.
Rough example:
<div id="dialog">
<p><span id="emailNotice"></span></p>
<button id="myButton">Submit</button>
</div>
Javascript:
$j('#dialog').dialog({
modal:true,
autoOpen: false,
width: 600,
buttons: {}
}
});
<!-- language: lang-js -->
buttons: [
{
text: "Delete that",
className: 'deleteButtonClass',
click: function() {
alert('foobar');
}
}
Find in jquery-ui-1.10.0.custom.css the class bellow and remove float: right;
.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset {
float: right;
}
Tested in jquery-ui-1.10.0.custom.css not in jquery-ui-1.8.7.custom.css

jQuery UI dialog modal set to true doesn't work for radiobuttons

When the dialog is set to modal it should disable all input elements, but I tried a simple example with a textbox and a radiobutton. When the dialog is opened the text-input is disabled as expected, but i still can check the radiobutton.
I used the example from the jQuery-ui demo and a simple html with just a input-textbox and the radio.
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="dialog-message" title="Download complete" style="display:none">
<p>
<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
Your files have downloaded successfully into the My Downloads folder.
</p>
<p>
Currently using <b>36% of your storage space</b>.
</p>
</div>
<input type="text"/>
<input type="radio" onClick="showDialog();"/>
<input type="radio"/>
</body>
</html>
And the jQuery:
function showDialog(){
jQuery(function() {
jQuery( "#dialog-message" ).dialog({
position: 'center',
zIndex: 4001,
draggable: false,
modal: true,
buttons: {
Ok: function() {
jQuery( this ).dialog( "close" );
}
}
});
});
}
Problem solved. It had to do with the css. Because I didn't use the default css or css created with theme roller I forgot to define the styling for ui-widget-overlay. After I copied the ovelay-styling from the jquery-ui css everything worked fine.
the css:
.ui-widget-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.ui-widget-overlay {
background: #666666 url(ui-bg_diagonals-thick_20_666666_40x40.png) 50% 50% repeat;
opacity: .50;
filter:Alpha(Opacity=50);
}

Ajax ModalPopupExtender with an edit form in ASP.NET MVC

I have an events calendar and on each event in the calendar there is an edit link which open up ajax ModalPopupExtender for editing the event information. The issue that I am facing right now is that the edit has to be in a form so it can update the information on the server..
How do I deal with this? And what would be the best way of doing this ?
You can use jQuery to accomplish the same functionality. I had to do this recently for a project because I didn't like the way the ModalPopupExtender was handling it. Unfortunately though I didn't build the drag click-and-drag functionality.
Here's the code for the ASP.NET and XHTML:
Somewhere on the page, you put trigger button:
<input type="button" value="Trigger Action" class="popup-trigger-delete" />
Panel Code:
<div class="popup-wrapper popup-wrapper-delete">
<div class="popup-top"></div>
<div class="popup-middle">
<div class="content">Are you sure you want to delete this from your project?</div>
<div class="controls">
<asp:Button ID="btnDelete_Yes" runat="server" CssClass="left" OnClick="btnDelete_Yes_OnClick" />
<input type="button" value="Cancel" class="right popup-background-delete-cancel" />
</div>
</div>
<div class="popup-bottom"></div>
</div>
<div class="popup-background popup-background-delete-track"></div>
Javascript / jQuery
var fadeInTime = 400;
var popupStatus = 0;
function loadPopup(wrapper){
//loads popup only if it is disabled
if(popupStatus==0){
$(wrapper).fadeIn(fadeInTime);
popupStatus = 1;
}
}
function disablePopup(wrapper, background){
if(popupStatus==1){
$(background).fadeOut(fadeInTime);
$(wrapper).fadeOut(fadeInTime);
popupStatus = 0;
}
}
function centerPopup(wrapper, background){
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $(wrapper).height();
var popupWidth = $(wrapper).width();
//centering
$(wrapper).css({
"position": "fixed",
"top": (windowHeight/2-100)-popupHeight/2,
"left": windowWidth/2-popupWidth/2,
"z-index" : "10000"
});
$(background).css({ "height": windowHeight });
}
//event handlers
var trigger = "input.popup-trigger-delete";
var wrapper = "div.popup-wrapper-delete";
var background = "div.popup-background-delete";
var dtpbc = "input.popup-background-delete-cancel";
$(document).ready(function(){
$(trigger).click(function(){ centerPopup(wrapper,background); loadPopup(wrapper); });
$(dtpbc).click(function(){ disablePopup(wrapper, background); });
$(document).keypress(function(e){ if(e.keyCode==27 && popupStatus==1){ disablePopup(wrapper,background); } });
});
CSS
div.popup-background-delete { display:none; }
div.popup-wrapper-delete { display:none; }
div.popup-wrapper { position:relative; display:none; display:block; width:350px; height:245px; padding:0; margin:0; z-index:5000; }
div.popup-top { position:relative; display:block; background-color:#ffffff; width:350px; height:40px; padding:0; margin:0; z-index:5000; }
div.popup-middle { position:relative; display:block; background-color:#ffffff; width:350px; min-height:165px; padding:0; margin:0; z-index:5000; }
div.popup-middle .content { position:relative; display:block; margin:0 auto; padding-top:20px; padding-bottom:10px; width:255px; z-index:5000; }
div.popup-middle .controls .left { position:absolute; top:0; left:80px; z-index:5000; }
div.popup-middle .controls .right { position:absolute; top:0; right:80px; z-index:5000;}
div.popup-bottom { position:relative; display:block; background-color:#ffffff; width:350px; height:40px; padding:0; margin:0; z-index:5000; }
div.popup-background { position:absolute; top:0; left:0; width:100%; height:100%; z-index:5000; background-color:#cbcbcb; opacity:0.2; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=20)"; filter: alpha(opacity=20); -moz-opacity:0.2; }
In order to get above sample working (sorry, can't comment), do this:
Change asp button to html button
Change "popup-background-delete-track" to "popup-background-delete"
In centerPopup, replace $(background).css({ "height": windowHeight }); with $(background).css({ "display": 'block' });
Remove all references to display:block in the CSS.

Resources