Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all 141367 articles
Browse latest View live

What is the additional effect of specifying tabindex = "-1" in the a tag? [duplicate]

$
0
0

I know the role of the 'tabindex' attribute. I also know that I use tabindex = "-1" if I don't want to focus through the tab key. But does applying tabindex = "-1" to the A tag also apply other side effects? When I click on the tag below, href = "javascript: void (0);" does not work and always goes to the top of the page.

<a href="javascript:void(0);" tabindex="-1">Click</a>

What's the problem? And how can I make it not move to the top even when a tag with the tabindex = "-1" attribute is clicked?


How to use other than default sans seriff family on HTML canvas?

$
0
0

Is there any way to use other font-family in HTML canvas?

  ctx.fillStyle = '#FFF';
  ctx.font = '43px Arial';
  ctx.textAlign = 'center';
  ctx.fillText(name, 220, 515);

This is using Arial and it works as it's in the sans-serif family, but I've tried by using other family and it fails.

I've tried to change Arial to Segoe-UI font like this:

ctx.font = '43px Segoe-UI';

But still no effect, how can I use segoe font on html canvas? If there's no way, is it proper if I save that text into images and import as images into the canvas?

Extracting full name from string using regex javascript

$
0
0

"Name: Roger LeftPhone: (848) 274-9377Email: rogerleft@trueworld.ai"

What is the regex expression (javascript) that I need to extract "Roger Left" from the string above?

Thanks!!

local timestamped date of utc timestamp (ut timestamp equalant)

$
0
0

i am using node binance api to fetch candles data, the api giving utc timestamp data but i want the local timestamp data. what i meant is

if i convert this timestamp data 1583756100000, it's give

GMT: Monday, March 9, 2020 12:15:00 PM

i want this timestamp date equivalent - (Your time zone: Monday, March 9, 2020 5:45:00 PM GMT+05:30)

i am tried this code , but not working

 var strTime = this.$moment(time).format('DD/MM/YYYY h:mm:ss:SSS A');
 strTime = this.$moment.utc(time).format('X');

Actual problem

my chart (github.com/C451/trading-vue-js) using timestamp date as x-axis . when i using node-binance-api (github.com/jaggedsoft/node-binance-api #binance.candlesticks ) api , they give utc timestamp response , so the candle data x-axis is showing utc candle chart , but i just want IST (+5.30) candle stick chart

Creating dynamic ul and li elements and adding collapsible functionality [duplicate]

$
0
0

I have dynamically loaded the data for Ul and li elements from Database using Jquery Ajax upon a checkBox event. The UL and Li data is loaded inside the featuresList div. And now wanted to create a collapse feature on the liParent class element.

If the Html code is static, then I am able to toggle the Ul elements but if I dynamically load the Ul and li element the click is not working and help me achieve the functionality Could anyone please help me with this.

Javascript& Html

$('.liParent ul').hide();
$('.liParent').click(function() {
  $(this).find('ul').slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="col-md-8 featureGrid" style="height: 100px; overflow: auto;border:2px solid #cccccc"><div class="featuresList" style="margin:10px 0 0 10px"><ul class="2"><li class="liParent" id="liRoleNameId">Feature<ul class="ulChild"><li class="liFeatures">Feature 1</li><li class="liFeatures">Feature 2</li><li class="liFeatures">Feature 3</li><li class="liFeatures">Feature 4</li><li class="liFeatures">Feature 5</li><li class="liFeatures">Feature 6</li><li class="liFeatures">Feature 7</li></ul></li></ul></div></div>

Explanation request about a promise in a vuejs sample

$
0
0

I have a little sandbox here with two components. A list of objects ("Groups" for the example) and a confirmation modal. The modal is triggered when a delete button is clicked. (This sandbox is extracted from another post in which I asked for different ways to send the result of the modal to the parent component, the GroupList).

The best solution for me was this one. However, while I understand the principle of javascript promises, I couldn't figure out how it works in this case. It works perfectly, but I don't like to use code that I don't understand.

In the ModalConfirmation, for the b-modal tag, these are the event that set the result of the modal. But how does vuejs / bootstrap-vue make the matching between that and the promise ?

@ok="resolvePromise(true)"
@cancel="resolvePromise(false)"
@close="resolvePromise(false)"

Because the promise constructor is called when the modal is showed and that's all...

Moreover, if I comment this

  resolvePromise: null,
  rejectPromise: null

in the modal component, it still works. Can someone explain me the flow of promise resolution in this case ?

Thanks in advance.

How to execute my content script on a newly opened chrome tab?

$
0
0

I am calling a Chrome extension from a web portal to open a URL in a new tab, and on the newly opened tab I want to perform executeScript:

manifest.json

"externally_connectable": {
  "matches": ["http://localhost:3000/*"]
},
"permissions": ["tabs", "http://*/*", "https://*/*"]

background.js

// listen to webportal
chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    a = chrome.tabs.create({ url: request.openUrlInEditor });
    chrome.tabs.insertCSS(a.id, { file: "combined.css" });
    chrome.tabs.executeScript(a.id, { file: "combined.js" });
  }
);

If I try to perform insertCSS and executeScript on extension click, it works fine

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.insertCSS(tab.id, { file: "combined.css" });
  chrome.tabs.executeScript(tab.id, { file: "combined.js" });
});

Show key as value in datatable

$
0
0

Hi I'm currently having trouble with datatable. My datasource is object and I want every first key in the object displayed as value in datatable. Here is my code.

  var my_data = {
          "content": [
             {
               "data_v1": [{"id" : 1}]
             },
             {
               "data_v2": [{"id" : 2}]
             },
             {
               "data_v3": [{"id" : 3}]
             }
          ]
       };



     $(document).ready(function() {
          $('#example').DataTable( {
              data:my_data,
              columns: [
                { data: 'content'
                }
              ]
          } );
      } );

What output I expect is this.

|  Content  |
-------------
   data_v1
   data_v2
   data_v3

Note: As long as posible, I don't want to use forloop or any kind of loop. TIA

Any help will be so much appreciated.


get session to php file called through ajax [closed]

$
0
0

main.php file

<body>
  <div class="container box">
   <h1 align="center">Live Add Edit Delete Datatables Records using PHP Ajax</h1>
   <br />
   <div class="table-responsive">
   <br />
    <div align="right">
     <button type="button" name="add" id="add" class="btn btn-info">Add</button>
    </div>
    <br />
    <div id="alert_message"></div>
    <table id="user_data" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>Frist Name</th>
       <th>Last Name</th>
       <th></th>
      </tr>
     </thead>
    </table>
   </div>
  </div>
 </body>
</html>

<script type="text/javascript" language="javascript">
 $(document).ready(function(){

  fetch_data();

  function fetch_data()
  {
   var dataTable = $('#user_data').DataTable({
    "processing" : true,
    "serverSide" : true,
    "order" : [],
    "ajax" : {
     url:"fetch.php",
     type:"POST"
    }
   });
  }

</script>

fetch.php

<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$columns = array('first_name', 'last_name');

$query = "SELECT * FROM user ";

**if(isset($_POST["search"]["value"]))
{
 $query .= '
 WHERE first_name LIKE "%'.$_POST["search"]["value"].'%" 
 OR last_name LIKE "%'.$_POST["search"]["value"].'%"';
}**

if(isset($_POST["order"]))
{
 $query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].''.$_POST['order']['0']['dir'].'';
}
else
{
 $query .= 'ORDER BY id DESC ';
}

$query1 = '';

if($_POST["length"] != -1)
{
 $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));

$result = mysqli_query($connect, $query . $query1);

$data = array();

while($row = mysqli_fetch_array($result))
{
 $sub_array = array();
 $sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="first_name">' . $row["first_name"] . '</div>';
 $sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="last_name">' . $row["last_name"] . '</div>';
 $sub_array[] = '<button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row["id"].'">Delete</button>';
 $data[] = $sub_array;
}

function get_all_data($connect)
{
 $query = "SELECT * FROM user";
 $result = mysqli_query($connect, $query);
 return mysqli_num_rows($result);
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  get_all_data($connect),
 "recordsFiltered" => $number_filter_row,
 "data"    => $data
);

echo json_encode($output);

?>

:::::::::::::::::::::::::::::::::::::::::: Now i'm trying to get the session variable $_SESSION["id"] value in fetch.php in line

if(isset($_POST["search"]["value"]))
    {
     $query .= '
     WHERE idd =$_SESSION["id"] AND first_name LIKE "%'.$_POST["search"]["value"].'%" 
     OR last_name LIKE "%'.$_POST["search"]["value"].'%"';
    }

Now i'm not getting the $_SESSION["id"] varibale value to fetch.php while calling it through ajax. but if i run fetch.php directly in browser the session varibale value is displayed while echo. I have no knowledge about ajax so i could not figure out the probelm so please help me out to get the seesion varibale value in fetch.php while calling from ajax. Please note that $_SESSION["id"] value is captured from login.php page

Getting error on adding angular-daterangepicker javascript files

$
0
0

My angular js code is as below. I am adding DateRangePicker with following library

var inApp = angular.module('myApp', ['daterangepicker']);

inApp.controller('incomeController', function($scope, $http) {
      console.log('income controller');
      $scope.datePicker = { date: {startDate: null, endDate: null} };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-daterangepicker/3.0.5/daterangepicker.js"></script><script src="https://raw.githubusercontent.com/fragaria/angular-daterangepicker/master/js/angular-daterangepicker.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-daterangepicker/3.0.5/daterangepicker.css" /><div ng-app="myApp" ng-controller="myController"><div class="form-group"><label for="optsCustom" class="control-label">Select Date</label><div><input date-range-picker class="form-control date-picker" type="text" ng-model="datePicker.date" /></div></div></div>

It is showing following error

     angular.js:14642 TypeError: el.daterangepicker is not a function
    at _init (angular-daterangepicker.js:135)
    at Object.link (angular-daterangepicker.js:156)
    at angular.js:1385
    at angular.js:10514
    at invokeLinkFn (angular.js:10520)
    at nodeLinkFn (angular.js:9909)
    at compositeLinkFn (angular.js:9149)
    at compositeLinkFn (angular.js:9152)
    at compositeLinkFn (angular.js:9152)
    at compositeLinkFn (angular.js:9152) "<input date-range-picker="" class="form-control date-picker ng-pristine ng-untouched ng-valid ng-isolate-scope" type="text" ng-model="datePicker.date">"
(anonymous) @ angular.js:14642
(anonymous) @ angular.js:11102
invokeLinkFn @ angular.js:10522
nodeLinkFn @ angular.js:9909
compositeLinkFn @ angular.js:9149
compositeLinkFn @ angular.js:9152
compositeLinkFn @ angular.js:9152
compositeLinkFn @ angular.js:9152
compositeLinkFn @ angular.js:9152
compositeLinkFn @ angular.js:9152
compositeLinkFn @ angular.js:9152
nodeLinkFn @ angular.js:9903
compositeLinkFn @ angular.js:9149
compositeLinkFn @ angular.js:9152
nodeLinkFn @ angular.js:9903
compositeLinkFn @ angular.js:9149
publicLinkFn @ angular.js:9014
(anonymous) @ angular-ui-router.min.js:11
(anonymous) @ angular.js:1385
invokeLinkFn @ angular.js:10520
nodeLinkFn @ angular.js:9909
compositeLinkFn @ angular.js:9149
publicLinkFn @ angular.js:9014
lazyCompilation @ angular.js:9405
R @ angular-ui-router.min.js:11
configUpdated @ angular-ui-router.min.js:11
(anonymous) @ angular-ui-router.min.js:11
t.sync @ angular-ui-router.min.js:11
Ir @ angular-ui-router.min.js:11
e.invokeHook @ angular-ui-router.min.js:11
(anonymous) @ angular-ui-router.min.js:11
e.runAllHooks @ angular-ui-router.min.js:11
(anonymous) @ angular-ui-router.min.js:11
processQueue @ angular.js:17000
(anonymous) @ angular.js:17044
$digest @ angular.js:18182
$apply @ angular.js:18480
done @ angular.js:12501
completeRequest @ angular.js:12727
requestLoaded @ angular.js:12655
load (async)
(anonymous) @ angular.js:12638
sendReq @ angular.js:12446
serverRequest @ angular.js:12198
processQueue @ angular.js:17000
(anonymous) @ angular.js:17044
$digest @ angular.js:18182
$apply @ angular.js:18480
bootstrapApply @ angular.js:1952
invoke @ angular.js:5040
doBootstrap @ angular.js:1950
bootstrap @ angular.js:1970
angularInit @ angular.js:1855
(anonymous) @ angular.js:33826
j @ jquery-3.2.1.min.js:2
k @ jquery-3.2.1.min.js:2
setTimeout (async)
(anonymous) @ jquery-3.2.1.min.js:2
i @ jquery-3.2.1.min.js:2
fireWith @ jquery-3.2.1.min.js:2
fire @ jquery-3.2.1.min.js:2
i @ jquery-3.2.1.min.js:2
fireWith @ jquery-3.2.1.min.js:2
ready @ jquery-3.2.1.min.js:2
S @ jquery-3.2.1.min.js:3
Show 10 more frames
angular.js:14642 TypeError: Cannot read property 'startDate' of undefined
    at Array.<anonymous> (angular-daterangepicker.js:95)
    at ngModelWatch (angular.js:29245)
    at Scope.$digest (angular.js:18202)
    at Scope.$apply (angular.js:18480)
    at done (angular.js:12501)
    at completeRequest (angular.js:12727)
    at XMLHttpRequest.requestLoaded (angular.js:12655)

How to resolve this?

How to convert JSON time stamp in javascript to date and time?

$
0
0

I am getting Time stamp as "2020-03-02T05:50:31.000Z"

How to convert this to Normal Readable Format with Date and Time Zone

Maximum size of an Array in Javascript

$
0
0

Context: I'm building a little site that reads an rss feed, and updates/checks the feed in the background. I have one array to store data to display, and another which stores ID's of records that have been shown.

Question: How many items can an array hold in Javascript before things start getting slow, or sluggish. I'm not sorting the array, but am using jQuery's inArray function to do a comparison.

The website will be left running, and updating and its unlikely that the browser will be restarted / refreshed that often.

If I should think about clearing some records from the array, what is the best way to remove some records after a limit, like 100 items.

How can I disable all links when the browser is in full screen mode?

$
0
0

How can I disable all links when the browser (Chrome / IE) is in full screen mode?

Because when user click the link (www / pdf link) in my web page, he will redirect to another page that does not contains a "Back" button to go back to previous page in full screen mode. And the full screen mode is required for access my web page.

Thanks!

JavaScript Undefined Exception

$
0
0

I am experiencing an annoying error that I only receive in Internet Explorer for some reason. I have an MVC application and in my _Layout.cshtml file I have @Scripts.Render("~/assets/js/bundled"). The bundled seems to be included fine and like I said everything works great in all tested browsers except IE11. When debugging with in IE I get:

0x800a1391 - JavaScript runtime error: 'MyJs' is undefined

The javascript file containing the definition for myjs is included in the bundle. The js (lets call it myjs.settings.js)file looks like this:

MyJs.settings = (function (parent, window, document, $) {

   function Initialize() { /* do stuff */ }
   function Something() { /* more stuff */ }

   var self = {
      Initialize: Initialize,
      Something: Something,
      Debug: debug
   }

   return self;

} (MyJs, window, document, jQuery));

MyJs.settings.Debug = false;
MyJs.settings.Initialize();

Any help would be greatly appreciated. Thanks.

My bot discord don't work. I don't know why

$
0
0

why this code don't work

client.on('message', message => {
if(message.content.startsWith(prefix + ' stop'))
{
  channel.send('Resetting...')
  client.destroy()
  client.login("xxx");
}
})

I have this error :

Help me please


Add async/await while using mysql package with Node JS

$
0
0

I am creating this Migration JS script using Node JS. Below is the full code of this migrate.js file.

const mysql = require("mysql");
var con = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
});

// Create Connection
con.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

  console.log('MySQL connected as id ' + con.threadId);
});

// Create Database
const db_name = 'nuxt_mysql';
con.query("CREATE DATABASE IF NOT EXISTS " + db_name, function (err, result) {
  if (err) throw err;
  console.log(`Database "${db_name}" created.`);

  // Select db
  con.changeUser({database : db_name}, function(err) {
    if (err) throw err;
    console.log(`Database "${db_name}" selected.`);

    // Create Tables
    createTables();
  });
});


// Create Tables
function createTables(){
  createArticlesTable();
  createUsersTable();

  // Close Connection after tables are created
  con.end();
  console.log('MySQL connection closed.');
}

// Create Articles Table
function createArticlesTable(){
  let sql = `CREATE TABLE IF NOT EXISTS articles (

      id INT AUTO_INCREMENT NOT NULL,
      title VARCHAR(255) NOT NULL,
      author VARCHAR(255) NOT NULL,
      body TEXT NOT NULL,
      date_added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      date_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

      PRIMARY KEY (id)
  )`;
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(`Table "articles" created.`);
  });
}

// Create Users Table
function createUsersTable(){
  let sql = `CREATE TABLE IF NOT EXISTS users (

      id INT AUTO_INCREMENT NOT NULL,
      full_name VARCHAR(255) NOT NULL,
      email VARCHAR(255) NOT NULL,
      password VARCHAR(255) NOT NULL,
      date_added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      date_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

      PRIMARY KEY (id),
      UNIQUE KEY (email)
  )`;
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(`Table "users" created.`);
  });
}

This script create a database first. Then it selects this db and then creates tables under it using different functions created for every table.

When I run node migrate.js , this is the output.

MySQL connected as id 257
Database "nuxt_mysql" created.
Database "nuxt_mysql" selected.
MySQL connection closed.
Table "articles" created.
Table "users" created.

Now the problem is, I want to close the mysql connection after all the tables have been created. And I think I will have to add async function somewhere. I am not very good with async/await so decided to post it.

react native : there is way to do an acordion table?

$
0
0

Is there a way to make an accordion display that when click then it will displays the table as in my example in accordion form?

this is the snack expo

import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';

export default class ExampleOne extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tableHead: ['this is my drop table'],
      tableData: [
        ['1', '2'],
        ['a', 'b'],
        ['1', '2'],
        ['a', 'b']
      ]
    }
  }

  render() {
    const state = this.state;
    return (
      <View style={styles.container}>
        <Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff'}}>
          <Row data={state.tableHead} style={styles.head} textStyle={styles.text}/>
          <Rows data={state.tableData} textStyle={styles.text}/>
        </Table>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
  head: { height: 40, backgroundColor: '#f1f8ff' },
  text: { margin: 6 }
});

How to implement multi role based authorization in React

$
0
0

I am working on application where I have different multi role ( admin, user,manager ) I want to protect route of admin from manager and general user also render UI based on user role . I tried but I am failed could someone please help me how to achieve my goal . Example will be appreciated

Thanks

Distributing WebComponent with license code in script.src relative path

$
0
0

I googled for this relative .. path trick for some time, no luck

I want to distribute a Custom Element/Web Component with at least some kind of license enforcement.
(yes, I know everything can be decoded)

  • I don't want or need any License code handling server side

    • User enters domain name on which element.js is going to be used

    • domain/LICENSECODE generated once

    • User downloads element.js

    • User configures <script> tag with license code :

Seems to work because:

  • Browser rewrites relative URLs:

    • server.com/LICENSECODE/ .. /path/element.js notation
    • creates the correct request URI: server.com/path/element.js
  • (obfuscated) element.js file can then use .getAttribute("src") to extract and validate the LICENSECODE against location.hostname

Question: Any pitfalls?

Code below works in Chrome, Edge, Firefox, Opera, haven't tested Safari

reference to jQuery used for Proof of Concept

<script id=elementname src="https://cdnjs.cloudflare.com/LICENSECODE/../ajax/libs/jquery/3.4.1/jquery.min.js"></script><script>
  let S = document.querySelector("#elementname");
  console.log(S.src); // No, now is the processed request URI
  console.log(S.getAttribute("src")); //original string
  //inside elements.js script:
  let code = document.querySelector('#elementname').getAttribute("src").split("/")[3];</script>

D3.3: Unable to represent time correctly into X-axis as Hour:Min:Sec format?

$
0
0

I have a list of dictionaries to represent data in a chart form using D3, but graph doesnt shows correctly as I am unable to parse time in a H:M:S format.

Here is the few lines:

           var data= [{ val: "0", timestamp : "10:20:45"},
                 { val: "0", timestamp : "10:21:45" },
                { val: "0" , timestamp : "10:22.45"},
                { val: "0" , timestamp : "10:20:45"},
              { val : "267", timestamp : "10:21:45" },
              { val : "0", timestamp : "10:22.45"},
                 { val: "0" , timestamp : "10:24:45"},
              { val : "128", timestamp : "10:25:45" },
               { val : "0", timestamp : "10:30.45"},
              ]
            var parseDate = d3.time.format("%H:%M:%S").parse;

          // Set the ranges
            var x = d3.time.scale().range([0, graphWidth]);
              var y = d3.scale.linear().range([graphHeight, 0]);

         // Define the axes
          var xAxis = d3.svg.axis().scale(x)
                   .orient("bottom").ticks(5);
            var yAxis = d3.svg.axis().scale(y)
             .orient("left").ticks(5);

I think , I have covered pretty much every thing , but it somehow doesn't work. I am new using D3 , need some help. full code- https://jsfiddle.net/gaurav10022/p8oxdcey/

Viewing all 141367 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>