When I click on the button, it hides tables content, hoisting - javascript

Goal:
I am trying to make all the table bodies hidden.
When I click on the arrow button, the table body will be shown.
Issue:
I can't hide the table bodies from the beginning.
And only the last table hides his content when I click on the button.
_ I am using a loop to create dynamic id that's why my function get only the last id on the loop
Thank You.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/stylesheet.css" integrity="" crossorigin="anonymous">
<link rel="stylesheet" href="css/dfirgo.css" integrity="" crossorigin="anonymous">
<meta charset="UTF-8">
<title>FRIGO</title>
</head>
<body>
<div class="container">
<div class="row">
<?php
include("php/connexion.php");
$rec = mysqli_query($conn, "SELECT * FROM espace");
echo" <div class=\"col\">";
$i=0;
while($row=mysqli_fetch_array($rec)) {
$i++;
echo"<table class=\"table\">
<thead class=\"thead-dark\">
<tr>
<th><img src=\"icones/neige.png\">ESPACE<button class='button12' value='tab".$i."' id='button12'onclick=\"myFunction()\"><img src=\"icones/élément1.png\" align=\"right\"></button></th>
</tr>
</thead>
<tbody>";
$_SESSION['case']='tab'.$i;echo"
<tr id='tab".$i."'>
<td >";
echo $row[1]."-".$row[2]."-".$row[3]."-".$row[4];
echo " </td>
</tr>
</tbody>
</table>";
} echo"</div>";
?>
</div>
<script>
function myFunction() {
var y = <?php echo json_encode($_SESSION['case']); ?>;
var x = document.getElementById(y);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<script src="css/popper.min.js.js" integrity="" crossorigin="anonymous"></script>
<script src="css/slim.min.js.js" integrity="" crossorigin="anonymous"></script>
<script src="css/bootstrap.min.js.js" integrity="" crossorigin="anonymous"></script>
</body>
</html>

So to understand, your problem is that you want to hide and show table bodies on click. Your listener is on your table header. There are several ways to do that. To go with your attempt just add a parameter to the onclick.
onclick="myFunction(this)"
Then you could just follow the hierarchy of your table to find your body element like this:
function myFunction(button) {
//th //thead //table //tbody
var x = button.parentNode.parentNode.parentNode.querySelector("tbody")
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
A different approach would be more understandable but I guess its fine. I also want to mention that toggling a class to the body would be better because then you don't have to worry about the initial display of the body which also could be flex or anything else. Something like...
.hide {
display: none;
}
if (x.classList.contains("hide")) {
x.classList.remove("hide")
} else {
x.classList.add("hide")
}
Another approach:
define a data-attribute on the button which contains the id of the body and use document.getElementById ( / )

Related

How to change text color using javascript function?

I'm trying to change text color depending on the number value.
<?php
$secure_num = 8;
$price_num = 4;
<script>
function change_color_text (num1) {
var rate_num = num1;
if(rate_num >= 7) {
rate_num.style.color = "#008000"; // green
} else if (rate_num >= 4) {
rate_num.style.color = " #FFFF00"; // yellow
} else {
rate_num.style.color = " #FF0000"; // red
}
return rate_num;
}
</script>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Service Rate</th>
<th class="has-text-align-center" data-align="center">Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Secure Rate</td>
<td class="has-text-align-center" data-align="center"><div class="Secure-Rate"><?php echo "<script> change_color_text($secure_num); </script>"?></div></td>
</tr>
<tr>
<td>Price Rate</td>
<td class="has-text-align-center" data-align="center"><div class="Price-Rate"><?php echo "<script> change_color_text($price_num); </script>"?></div></td>
</tr>
</tbody>
</table>
</figure>
?>
So what I'm trying to do is that if $secure_num is 8 then the number '8' (green color) should be echoed, and if $price_num is 4 then the the number '4' (red) should be echoed on the screen. I don't use html format 'cause I'm writing this code on the wordpress theme code(mostly php file).
This code will definitely give an error, "cannot read value of undefined"
This has to do with DOM manipulation.
In this code, JavaScript engine doesn't understand what element style color you're trying to change.
A way to fix this will be
const rate_num = document.querySelector(".class")
Where .class is the class name of whatever text you're trying to change in the HTML.
you can write this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="demo"></div>
<script>
function change_color_text (num1) {
var rate_num = num1;
if(rate_num >= 7) {
document.getElementById('demo').innerHTML="green";
document.getElementById('demo').style.color="green";
} else if (rate_num >= 4) {
document.getElementById('demo').innerHTML="yellow"; // yellow
document.getElementById('demo').style.color="yellow";
} else {
document.getElementById('demo').innerHTML="red" // red;
document.getElementById('demo').style.color="red";
}
return rate_num;
}
</script>
</body>
</html>
<?php echo "<script> change_color_text(8) </script>"?>

Can't overwrite bootstraps column width limit

I am trying to make a table that will display information on a page. I DO NOT want the text to wrap. I've done so much searching and I can't seem to fix it! I'm using bootstrap and I have no idea how to override whatever type of limit is happening here. Please help!
Image of webpage
HTML/PHP for webpage
<?php
function createTable(){
$maxDays=date('t'); //gets the number of days in a month
$currentDayOfMonth=date('j'); //gets the current day
$rows = 14; // define number of rows
$cols = $maxDays;// define number of columns
// loops through and creates the table
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
for($td=1;$td<=$cols;$td++){
echo "<td class='tableCells'>654 kwh</td>";
}
echo "</tr>";
}
}
function writeDays(){
$lastDayUTS = mktime (0, 0, 0, date("m"), date('t'), date("Y"));
$lastDay = date("d", $lastDayUTS);
$monthName = date("M", $lastDayUTS);
//writes the days above the table
for($n=1;$n <= $lastDay;$n++){
echo "<th>$monthName $n</th>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-lg-9">
<table class='table table-hover'>
<thead>
<!-- writes the days above the table -->
<?php writeDays(); ?>
</thead>
<tbody>
<?php
// loops through and puts values into the table
createTable();
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
The end goal is to have this embedded in a page and overflow the x axis so you can scroll horizontally. I want the text to all be on one line (not wrapped). Any help is greatly appreciated!!!

How to insert row in HTML tablesorter table body in javascript/node.js?

I have made a function test tool for my company app using html/css/javascript/node.js/express/tablesorter.
My test tool is successfully performed the function tests.
My table style is from opensource 'Tablesorter'.
This is edit screen. The file is .ejs format. So, Node.js server render the file to html dynamically.
But, I wonder how to insert the row additionally in this table. So, I searched to solve the problem and got some solution like below.
for (var i in rList) {
var table = document.getElementById("ID_Table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var list = rList[i].split(" ");
cell1.innerHTML = list[0];
cell2.innerHTML = list[1];
}
But, this way is incomplete. The result is like this.
The 'tablesorter' style is not applied to additional rows. I don't know how to solve this.
<!DOCTYPE html>
<html>
<head>
<!-- Character Set -->
<meta charset="utf-8">
<!-- Title -->
<title><%= title %></title>
<!-- Style -->
<link rel='stylesheet' href='/stylesheets/style.css'/>
<!-- JS -->
<script src="/javascripts/indexCore.js"></script>
<!-- jQuery -->
<script src="/opensources/tablesorter/docs/js/jquery-latest.min.js"></script>
<script src="/opensources/tablesorter/docs/js/jquery-ui.min.js"></script>
<!-- Tablesorter: theme -->
<link class="theme default" rel="stylesheet" href="/opensources/tablesorter/css/theme.default.css">
<link class="theme blue" rel="stylesheet" href="/opensources/tablesorter/css/theme.blue.css">
<link class="theme green" rel="stylesheet" href="/opensources/tablesorter/css/theme.green.css">
<link class="theme grey" rel="stylesheet" href="/opensources/tablesorter/css/theme.grey.css">
<link class="theme ice" rel="stylesheet" href="/opensources/tablesorter/css/theme.ice.css">
<link class="theme black-ice" rel="stylesheet" href="/opensources/tablesorter/css/theme.black-ice.css">
<link class="theme dark" rel="stylesheet" href="/opensources/tablesorter/css/theme.dark.css">
<link class="theme dropbox" rel="stylesheet" href="/opensources/tablesorter/css/theme.dropbox.css">
<link class="theme metro-dark" rel="stylesheet" href="/opensources/tablesorter/css/theme.metro-dark.css">
<!-- Tablesorter script: required -->
<script src="/opensources/tablesorter/js/jquery.tablesorter.js"></script>
<script src="/opensources/tablesorter/js/widgets/widget-filter.js"></script>
<script src="/opensources/tablesorter/js/widgets/widget-stickyHeaders.js"></script>
<script id="js">
$(function(){
/* make second table scroll within its wrapper */
$('#ID_Table').tablesorter({
widthFixed : true,
headerTemplate : '{content} {icon}', // Add icon for various themes
widgets: [ 'zebra', 'stickyHeaders', 'filter' ],
widgetOptions: {
// jQuery selector or object to attach sticky header to
stickyHeaders_attachTo : '.wrapper' // or $('.wrapper')
}
});
$("#ID_Table tbody").click(function () {
//$(this).addClass('selected').siblings().removeClass('selected');
//alert('a');
});
});
</script>
<script>
$(function() { //이 부분은 렌더링 되자마자 실행되는 부분
window.includeCaption = true;
$('.caption').on('click', function(){
includeCaption = !includeCaption;
$(this).html( '' + includeCaption );
$('#ID_Table').each(function(){
if (this.config) {
this.config.widgetOptions.stickyHeaders_includeCaption = includeCaption;
this.config.widgetOptions.$sticky.children('caption').toggle(includeCaption);
}
});
});
// removed jQuery UI theme because of the accordion!
$('link.theme').each(function(){ this.disabled = true; });
var themes = 'dropbox blue green grey ice black-ice dark default metro-dark', //테마 순서
i, o = '', t = themes.split(' ');
for (i = 0; i < t.length; i++) {
o += '<option value="' + t[i] + '">' + t[i] + '</option>';
}
$('select:first')
.append(o)
.change(function(){
var theme = $(this).val().toLowerCase(),
// ui-theme is added by the themeswitcher
files = $('link.theme').each(function(){
this.disabled = true;
})
files.filter('.' + theme).each(function(){
this.disabled = false;
});
$('table')
.removeClass('tablesorter-' + t.join(' tablesorter-'))
.addClass('tablesorter-' + (theme === 'black-ice' ? 'blackice' : theme) );
}).change();
});
</script>
</head>
<body>
<div id="header">
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
Main
Edit
Blank
<hr/>
</div>
<div id="wrap">
<div id="Main_Screen">
<input type="button" value="로딩" id="btn" onclick="dynamicLoadScript_Main('/temps/MainScript.js', '/temps/WrapScript.js')"></input>
<input type="button" value="수행" id="btn1" onclick="Automation()"></input>
<button type="button">결과 리스트 출력</button>
</div>
<div id="List_Screen" class="narrow-block wrapper">
Theme: <select></select>
<table id="ID_Table" class="tablesorter" border="0" cellpadding="0" cellspacing="1">
<thead>
<tr>
<th>Function</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
This is my .ejs File.
And, this is printResult Function in indexCore.js.
function printResult(){
var rList = resultList.split('\n');
for (var i in rList) {
var table = document.getElementById("ID_Table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var list = rList[i].split(" ");
cell1.innerHTML = list[0];
cell2.innerHTML = list[1];
}
}
You can edit and apply your logic at the .ejs file directly at your backend as your client side solution seems to be run after table being initialized by Tablesorter. You can also try to implement your client side solution adding the rows to table first then initialize Tablesorter. Good Luck!

$ is not defined in JQuery [duplicate]

This question already has answers here:
JQuery - $ is not defined
(36 answers)
Closed 7 years ago.
Let me show you all, i put this code in a file called consultas.php
CONSULTAS.PHP
This file shows the table with data, at the end of column called folio id="'.$row["folio"].'" when i clicked there this shows me and towards to VISTAPREVIA.PHP for more data about this folio but in paging #1 it works very well and now when i'm going to paging #2 i clicked again and doesn't work because doesn't show me anything, the error says me: Uncaught ReferenceError: $ is not defined
<script type="text/javascript">
$(document).ready(function() {
var table = $('#registros').DataTable({
"paging": true
});
//new $.fn.dataTable.AutoFill( table );
$('.back').on("click", function(event)
{
event.preventDefault();
location.reload();
});
$('.modificar').on("click", function(event)
{
event.preventDefault();
//Cargamos el contenido del enlace
var f = $(this).attr('id');
$('#mainContainer').load(this.href, {folio: f}, function(){
});
});
$('.vistaprevia').on("click", function(event)
{
event.preventDefault();
//Cargamos el contenido del enlace
var f = $(this).attr('id');
$('#mainContainer').load(this.href, {folio: f}, function(){
});
});
$('.detalle').on("click", function(event)
{
event.preventDefault();
var f = $(this).attr('id');
$('<div></div>').load(this.href, {folio: f}).modal();
});
});
</script>
REGRESAR ATRÁS
<h1 class="titPer">CONSULTA DE LA TABLA</h1>
<div class="tabla">
<table id="registros" class="display" cellspacing="0">
<thead>
<tr>
<th>Folio</th>
<th>Estatus</th>
<th>Punto de Venta</th>
<th>Usuario</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_array($consulta)) {
?>
<tr>
<td><?=$row['folio']?></td>
<td><?=$row['estatus']?></td>
<td><?=$row['punto_venta']?></td>
<td><?=$row['usuario']?></td>
<td>
<?php
if($_SESSION['permisos'] == 'VENDEDOR' || $_SESSION['permisos'] == 'JEFESUC' || $_SESSION['permisos'] == 'EMBARQUES'){
echo '
<center>
<a class="modificar icon-pencil" href="includes/vistaPrevia.php" id="'.$row["folio"].'"></a>
|
<a class="detalle icon-eye-plus" href="includes/lightbox.php" id="'.$row["folio"].'"></a>
</center>
';
}else{
echo'
<center>
<a class="vistaprevia icon-eye-plus" href="includes/vistaPrevia.php" id="'.$row["folio"].'"></a>
</center>
';
}
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
VISTAPREVIA.PHP
<?php session_start(); ?>
<head>
<link href='http://fonts.googleapis.com/css?family=PT+Sans+Narrow' rel='stylesheet' type='text/css'>
</head>
REGRESAR ATRÁS
<h1 class="titPer">ACTUALIZACIÓN DE DATOS</h1>
<!-- <form action="includes/"></form> -->
<?php
if($_SESSION['permisos'] == 'CALIDAD'){
include('upRegCal.php');
}
?>
<form action="includes/edit.php" enctype="multipart/form-data" id="formAct" method="POST" name="enviarForm">
<?php
if($_SESSION['permisos'] == 'VENDEDOR' || $_SESSION['permisos'] == 'JEFESUC' || $_SESSION['permisos'] == 'EMBARQUES'){
include('upRegUser.php');
}
if($_SESSION['permisos'] == 'ADMINISTRADOR'){
//include('upRegCal.php');
echo "Hola Administrador";
}
?>
</form>
last
INDEX.PHP
i have to assure this part because i put the correct Jquery scripts but i don't know why and i couldn't find the problem and yes i use the Datables Scripts
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/>
<title>Bienvenido</title>
<script src="js/jquery-1.11.2.js"></script>
<script src="js/funciones.js"></script>
<script src="libs/datatables/media/js/jquery.dataTables.js"></script>
<script src="libs/datatables/extensions/AutoFill/js/dataTables.autoFill.js"></script>
<script type='text/javascript' src='js/jquery.simplemodal.js'></script>
<script type='text/javascript' src='js/basic.js'></script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,300,400,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css" type="text/css"/>
<link rel="stylesheet" href="css/estilos.css" type="text/css"/>
<link rel="stylesheet" href="css/estilosForm.css" type="text/css"/>
<link type='text/css' href='css/basic.css' rel='stylesheet' media='screen' />
<link rel="stylesheet" href="libs/datatables/media/css/jquery.dataTables.css" type="text/css"/>
<link rel="stylesheet" href="libs/datatables/extensions/AutoFill/css/dataTables.autoFill.css" type="text/css"/>
</head>
<body>
<div class="fondoHeader"></div>
<header class="shadow">
<nav>
<?php
if(isset($_SESSION['usuario']))
include('includes/btnSiSession.php');
else
include('includes/btnNoSession.php');
?>
</nav>
</header>
<div id='mainContainer'>
<?php
include('includes/bienvenido.php');
if(isset($_SESSION['usuario'])){
echo "<script language='JavaScript'>";
// echo "document.getElementById('login').style.display='none'";
echo "document.getElementById('login').style.visibility='hidden'";
echo "</script>";
}
else{
echo "<script language='JavaScript'>";
// echo "document.getElementById('login').style.display='block'";
echo "document.getElementById('login').style.visibility='visible'";
echo "</script>";
}
?>
</div>
<div class="clear"></div>
<footer>
<?php
include('includes/footer.php');
?>
</footer>
</body>
</html>
UPDATE
i put this code jQuery CDN script
<script src="ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#registros').DataTable({
"paging": true
});
//new $.fn.dataTable.AutoFill( table );
$('.back').on("click", function(event)
{
event.preventDefault();
location.reload();
});
$('.modificar').on("click", function(event)
{
event.preventDefault();
//Cargamos el contenido del enlace
var f = $(this).attr('id');
$('#mainContainer').load(this.href, {folio: f}, function(){
});
});
$('.vistaprevia').on("click", function(event)
{
event.preventDefault();
//Cargamos el contenido del enlace
var f = $(this).attr('id');
$('#mainContainer').load(this.href, {folio: f}, function(){
});
});
$('.detalle').on("click", function(event)
{
event.preventDefault();
var f = $(this).attr('id');
$('<div></div>').load(this.href, {folio: f}).modal();
});
});
</script>
In consultas.php, you must include JQuery (<script src="js/jquery-1.11.2.js"></script>) before using it, before your <script>.
In web, each page is different, then you must add jQuery in each one.
example
<script src="js/jquery-1.11.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/* ... */
});
</script>
In some cases you have to use jQuery instead of $.
2nd option: jQuery(document).ready(function($) {
After this you can use $ as synonym for jquery.
This error is because you're missing the JQuery library. If you are including your Javascript libraries(including JQuery) at the bottom of your page(footer), you can either
Include the JQuery library at the top of the page
OR
make your Javascripts functions into a common js file and include it at the footer just below the Jquery include.
Here is the link to Jquery CDN

Display tweets retrieved from database after onclick function

I am using JavaScript, PHP and HTML for my application. I have a SQL database that contains tweets. I need to query from database and display tweets after the keyword (connecting to a hyper tree) is clicked. I have researched and tried to include an external php file (generatetweets.php) inside myFunction() at index.php. However it's not working. Anyone can enlighten me or any reference for me to guide?
Thank you in advance.
Extracted example2.js, where child.name refers to the keyword from hyper tree
onComplete: function(){
//Log.write("done");
//Make the relations list shown in the right column.
//ONCLICK FUNCTION FOR KEYWORDS TO LOAD RELATED TWEETS
var node = ht.graph.getClosestNodeToOrigin("current");
var html = "<div><b>Keyword: " + node.name + "</b></div>";
html += "<ul>";
node.eachAdjacency(function(adj){
var child = adj.nodeTo;
var childName=child.name;
html += '<a onClick="myFunction('+'''+child.name+'''+')"><li>'+child.name + '</li></a>';
});
html += "</ul><br />";
$jit.id('inner-details').innerHTML = html;
}
generatetweets.php
<?php
// connect to the database
include "mysqli.connect.php";
// create your SQL statment to retrieve everything from
// the users table
$sql = "SELECT * FROM post WHERE content LIKE '%school%' ORDER BY date DESC";
// run the query
$result = $mysqli->query($sql);
// check for error
if ($mysqli->errno)
{
error_log($mysqli->error);
echo "<br />Something's wrong";
exit();
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<head>
</head>
<body>
<?php
// Check if there are records in the first place
if ($result->num_rows < 1)
{
echo "<h3>No records found</h3>";
}
// Iterate through the records
$counter = 0;
// Use fetch_array to get rows returned one at a time
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<table>
<tr id="tweetlist">
<td style="width:50px">
<!-- name goes here -->
<!--<img id="img<?=$counter?>" style="padding-right:5px" src="<?=$row["displaypicture"]?>"></img>-->
</td>
<td>
<!-- email textfield goes here -->
<span id="date<?=$counter?>" style="color:#CCFF33">[<?=$row["date"]?>] </span>
<span id="name<?=$counter?>">#<?=$row["username"]?>: </span>
<span id="emailTxt<?=$counter?>"><?=$row["content"]?> <span/>
</td>
</tr>
</table>
<br/>
<?php
$counter++;
}
$result->free();
$mysqli->close();
?>
</body>
Extracted index.php, to display tweets in div "demo"
<body onload="init();">
<!-- Header -->
<div id="header" class="container">
<!-- Logo -->
<h1 id="logo">Mood</h1> <!-- logo from style-n1.css -->
<div id="center-container">
<div id="infovis"></div>
</div>
<div id="right-container">
<div id="inner-details"></div>
<div id="log"></div>
<div id="node_name"></div>
<div id="demo" style="padding-left: 50px">
<script type="text/javascript">
function myFunction() {
$("#demo").load("generatetweets.php");
}
</script>
</div>
</div>
</div>
</body>
Hypertree is referenced from http://philogb.github.io/jit/static/v20/Jit/Examples/Hypertree/example2.html
I obtained tweets using nodejs and append it to div. Here is my code.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
#<input type="text" id="tag" class="hash"/>
<button>submit</button>
</form>
<div id="tweets"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/socket.io/socket.io.js"> </script>
<script>
var socket = io.connect("link to nodejs");
var link;
var tag;
var a;
function debounce(func, wait, immediate){
var timeout;
return function(){
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply();
}, wait);
if (immediate && !timeout) func.apply();
};
};
var func = debounce(function(){
$('#tweet').html("");
socket.emit('message', $('#tag').val());
tag=$('#tag').val();
link="http://twitter.com/hashtag/"+tag;
a="<a href="+'link'+" target='_blank'> #"+tag+"</a>";
},1000);
$('.hash').keypress(func);
$('.hash').on('change',function(){
$('#tweet').html("");
socket.emit('message', $('#tag').val());
tag=$('#tag').val();
link="http://twitter.com/hashtag/"+tag;
a="<a href="+'link'+" target='_blank'> #"+tag+"</a>";
});
socket.on('message', function(msg){
console.log(msg.length);
$('#tag').val('');
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig ;
var hashregex= /(#[a-z0-9][a-z0-9\-_]*)/ig;
console.log(link);
for(var i = 0; i < msg.length; i++){
msg[i].tweettext=msg[i].tweettext.replace(hashregex,a);
msg[i].tweettext=msg[i].tweettext.replace(regex, "<a href='$1' target='_blank'>$1</a>");
$('#tweets').after('<div>UserName: ' + msg[i].username+ '</div>');
$('#tweets').after('<div>Text: ' + msg[i].tweettext+ '</div>');
$('#tweets').after('<div>Time: ' + msg[i].timedate+ '</div>');
$('#tweets').after('<br></br>');
}
});
</script>
</body>
<html>

Categories

Resources