Can’t copy text from webpage?

Sometimes I come upon a website that I cannot copy text from a HTML web page. Simply cannot click and highlight the lines I try to select for copying. I thought that my browser/mouse was not working. But I go to other sites, I am able to highlight/copy normally. They must’ve done something on that page probably to prevent content from being lifted of the page easily?

Why is this and how do they do it? Is this a javascript in the page that prevents me from copying?

ANSWER

Could be a script on the webpage. I’m certain that can be done or already been done through Javascript before.

I know that the same effect can be achieved via CSS alone. It is easier, cleaner and does not add to another Javascript messing up or slowing down a site. I prefer this method over the other.

Below are the CSS lines that does what you want. Different ones for different browsers. It is vendor specific for some, but does the same exact thing.

   user-select: none; /* Supported by Chrome, Firefox & Opera */
  -moz-user-select: none; /* Firefox (older) */
  -ms-user-select: none; /* Edge */
  -khtml-user-select: none; /* Konqueror */
  -webkit-touch-callout: none; /* Safari for iOS */
  -webkit-user-select: none; /* Safari for Mac */

Try it out. You can make it for entire page/site.

* {
     /* CSS lines go here */
}

Or you can make it so only targeted content will have it using Class or ID selectors.

#text-no-select {
     /* ID selector -  CSS lines go here */
}

.text-no-select {
     /* Class selector -  CSS lines go here */
}

Be aware this does not totally prevent anyone from copying content on a website. There are many other ways to go around this or even with a Javascript impementation. It is a minor roadblock.

Javascript(Typescript) Generic Api Call Service

I’m building a SSR application with React and Next js and this application will communicate with with the Rest service already created. Application must send request to Rest service on both client side and server side. So I have to create one ApiCall service works both client side and server side. I tried build something but I think its not good.

ApiCall.ts

export function apiCall<T extends BaseQuery>(
 query: T,
 options?: UseQueryOptions<T>,
 ctx?: GetServerSidePropsContext
): QueryResult<T> {
    const [data, setData] = GState()(null);
    const [error, setError] = GState()(null);
    const [loading, setLoading] = GState()<Boolean>(true);

    const headersWithToken = headers(TOKEN.get(ctx.req));
    const variables: any = options.variables;

    const queryP = query(variables, headersWithToken)
    .then((respData) => {
       setData(respData);
       setLoading(false);
       return respData;
    })
    .catch((e) => {
       setLoading(false);
       setError("ERROR");
    });

    return {
       data: data,
       error: error,
       loading: loading,
       query: queryP,
   };
}

GState.ts Closure

const GState = function () {
   let _val;

   function useState<T>(initialValue: T) {
     _val = _val || initialValue;

     function setState(newVal: T) {
        _val = newVal;
     }

     function getState(): T {
       return _val;
     }
     return [getState, setState];
   }
return useState;
};

export default GState;

Api endpoints

const getCredit = (headers: {}) => Promise<ICreditResponse> = (headers) => {
  return ApiService.setHeaders(headers).getReq({
    route: "/credits/my",
    isPrivate: true,
  });
};

const healthCheckReq = (headers: {}) => Promise<string> = (headers) => {
  const apis = ApiService;
  return apis.getReq({ route: `/health`, isPrivate: false });
};

const getMerchantShippingDays = (
  s: {
    merchantId: string;
  },
  headers: {}
) => Promise<IShippingDaysResponse> = ({ merchantId }, headers) =>
    ApiService.setHeaders(headers).getReq({
      route: `/shippingDays/merchant/${merchantId}`,
      isPrivate: true,
});

Example Usage :

export default function Health({ health }: HealthProps) {

  const { data: getHealthData, loading: getHealthLoading } = apiCall(
     queryEndpoints.healthCheckReq,
     { variables: { id: "1" } }
  );

  const __ = (
     <AppContainer>
        <Container fluid>
           {!getHealthLoading() && getHealthData().map(data => 
              <Row>{data.id}</Row>
           )}
       </Container>
    </AppContainer>
 );

  return __;
}

export const getServerSideProps: GetServerSideProps = async (
  ctx: GetServerSidePropsContext
  ) => {
     const { data: healthData, loading: healthLoading, query } = apiCall(
       queryEndpoints.healthCheckReq,
       { variables: { id: "1" } },
       ctx
    );

    await query;

    return { props: { health: healthData } };
};

I need advice for that api service. How can I improve that or if I don’t need this service how can I do request to rest service with generic functions

Go to Source
Author: zblash

What framework to use with excel for data frame in javascript like pandas?

I am trying to create a website that displays values from a .csv file that matches a certain criteria similar to how you can filter data from a dataframe in the pandas framework in python. I am not sure if there is anything similar in javascript. If not, what framework should I use to do this using python for web development?

Go to Source
Author: chibiw3n

Doing a validation check on a AJAX post and returning the error message

I have an AJAX post that does this

  $.ajax({
                    type: "POST",
                    url: "@MyWebSite.Url/myController/myView",
                    contentType: "application/json; charset=utf-8",
                    data:
                    JSON.stringify({ myModel: myData }),
                    dataType: "json",
                    traditional: true,
                    success: function () {
                        alert('Success!');
                    },
                    error: function () {
                        alert('Error! ');
                    }

My controller does the validation check but it is not correctly returning the error message.
This is what my controller looks like

 if (totalQty < part.QtyInItem)
                    {
                        //ModelState.AddModelError("", "There is " + part.QtyInItem + " of Part " + part.PartName + " used in item " + part.ItemID + " but you only handled " + totalQty + ". Please verify you are handling all parts used in the item.");
                        //RedirectToAction("myControler", myModel);
                        return this.Json(new { success = false, message = "There is " + part.QtyInItem + " of Part " + part.PartName + " used in item " + part.ItemID + " but you only handled " + totalQty + ". Please verify you are handling all parts used in the item." });
                    }

When I tried adding an error to the model state it just returned “ERROR!” and not the error message I had associated with it. And when I try doing the this.JSON return it returns “success” to the view and not the error message.

How can I do this validation check for my AJAX post

Go to Source
Author: ryan

js files occasionally failing to load

We have a newly configured php7 16cpu 32gb RAM Linux server.
Plenty of power for what we need.

We have a basic form on a page that requires a login.

However, sometimes when a user lands on the page, the js files fail to load which in turn prevents them from logging in.

This doesn’t happen every time, but often enough to where we cannot use the newly configured server.

KeepAlive is enabled, as seen by this curl command:

Content-Type: text/html; charset=UTF-8 Content-Length: 0 Connection: keep-alive

I have attached an image of what we’re seeing.

Could this have anything to do with server/Apache configuration, as we notice the js files always fail at the 10 second mark.

Btw,

enter image description here

Go to Source
Author: mcs

jquery: adding rows at the bottom of a table make table y-scroll jump into to start position

I’ve created a “log viewer” method that contains a table with a fixed header; initially this method loads 200 lines into the table, and will load more lines on demand. If you scroll down (until certain y-scroll % ) method will do a request to server asking for a further 100 lines from bottom, then will catch these lines and append them at bottom of this table…

Similar behaviour is for the top if y-scroll reach certain % of table ‘y-scroll’ and the top line is not the initial line, it will request 100 (or the number of lines to the top if less than 100) and insert those lines into the top.

This is working perfectly so I’m very satisfied with it; as it is what I wanted.

All rows are kept in a “<tbody>” block

Now Here is my problem: in some occasions when method is adding new lines at the bottom of the table, the table ‘y-scroll’ jump from its position to start position which is not what I want, as it makes experience very annoying…

Expected behaviour will be: table y-scroll will move slightly up while is appending new rows into the bottom of the table.

This happens if you try to scroll yourself picking the scroll bar with the mouse and dragging it yourself, or pressing PgDown key, or pressing DownArrow Key…

Here is the code of this method:

$.getJSON(
        "get_logfile",
        {
          "logfile_hash_key": logfile_hash_key,
          "initial_line":  initial_line,
          "requested_rows": requested_rows,
          "web_request": true
        },

        function(data)
        {
              // I need to reverse the array to start inserting on the table, because otherwise inserted
              // lines will be reversed
              //
              // If request is from top...
              if (requested_rows < 0) {
                    new_initial = initial_line + requested_rows
                    if (new_initial < 0){
                        initial_line = 1
                    }
                    sinitial_line=document.getElementById("initial_line").attributes["data-value"]
                    sinitial_line.value = new_initial
                    starting_row = 0
                    data.reverse()
              }
              else { // if Request is from bottom...
                    new_final = initial_line + requested_rows
                    if (new_final > file_line_count) {
                         new_final = file_line_count
                    }
                sfinal_line=document.getElementById("final_line").attributes["data-value"]
                last_row_on_table=document.getElementsByClassName("tb-Log-Viewer")[0].rows.length - 1

                starting_row = -1

                sfinal_line.value = new_final

              }

              $.each(data, function(key,value) {
                    row = table.insertRow(starting_row)
                    cell=[]
                    for(cell_n=0; cell_n < value.length; cell_n++){
                        cell[cell_n] = row.insertCell(cell_n)
                        // verify cell has a "String" value
                        //
                        if (data[key][cell_n].__proto__ == "".__proto__) {
                            cell[cell_n].innerHTML = data[key][cell_n]
                            if (cell_n == 0) {
                               cell[cell_n].style = "text-align:center"
                               cell[cell_n].className = "Line"
                            }
                        }
                        // Check value for given cell is an array
                        //
                        if (data[key][cell_n].__proto__ == [].__proto__) {
                            cell[cell_n].innerHTML = data[key][cell_n][1]
                            attributes = data[key][cell_n][0].replace("style=","").replace(/'/g,"").trim().replace(" ",";")
                            cell[cell_n].style = attributes.replace("bgcolor=","background-color:")
                        }
                    }
              }
          )
        }
     )

Here is the HTML portion of this that define the table (All this is being generated by a python code):

...
<table class="logviewer" width="85%" border=1 cellpadding=10 cellspacing=0>
<thead class="th-Log-Viewer">
<style>
.Line {
   width: 70px;
}

.Timestamp {
   width: 170px;
}

.Severity {
   width: 80px;
}

.Message {
   width: 1800px;
}

</style>

<tr class="tr-Log-Viewer">
<th  class="header-Line">Line</th>
<th  class="header-Timestamp">Timestamp</th>
<th  class="header-Severity">Severity</th>
<th  class="header-Message">Message<div class="rows-data"><table><tr><td><span id="scroll-action"></span></td><td><span id="top-row"></span></td><td><span id="bottom-row"></span></td></tr></table></div></th>
</tr>
</thead>
<tbody class="tb-Log-Viewer" onscroll="Log_Viewer(this)">

<tr>
<td class="Line" style='text-align:center'><a id='1'>1</a></td>
<td class="Timestamp" style='text-align:center'>2020-07-07 08:19:48</td>
<td class="Severity" style='text-align:center' bgcolor=#3cb371>INFO</td>
<td class="Message" style='text-align:left'>[INFO ] 2020-07-07T08:19:48,516Z [main] cliutils.CliWrapperBase. - Application Args: generate-node-info</td>
</tr>

...
</tbody>
</table>

So what could be causing this table y-scrolling jump into starting position???

Thank you.

I’ve asked this question on StackOverflow but it has couple of weeks and no answer…

Go to Source
Author: Larry

Fade-in Fade-out doesn’t work in WordPress

I have back-to-top script with an arrow icon which appears when scrolling down and disappears when the page content is on top. Works perfect, but when I insert the script in WordPress the scrollTop part of the script works but not the fade-in and fade-out effect.

Any solution?

jQuery('body').prepend('<a href="#" class="back-to-top">Back to Top</a>');
var amountScrolled = 300;
$(window).scroll(function() {
    if ( $(window).scrollTop() > amountScrolled ) {
        $('a.back-to-top').fadeIn('slow');
    } else {
        $('a.back-to-top').fadeOut('slow');
    }
});

$('a.back-to-top, a.simple-back-to-top').click(function() {
    $('html, body').animate({
        scrollTop: 0
    }, 700);
    return false;
});
body {background:#FEF1D4; height:1000px}

.back-to-top {
    display: none;
    width: 4.75rem;
    height: 4.75rem;
    text-indent: -9999px;
    position: fixed;
    z-index: 1500;
    left: 0.5rem;
    bottom: 1rem;
    background: url(https://static.thenounproject.com/png/1920879-200.png) no-repeat center 43%;
    background-size: contain;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This is the WordPress result:

enter image description here

Go to Source
Author: Danielillo

Should child nodes have a reference to their parents?

Let’s say you are engineering a chat room software.

let client = new Client();
let room = rooms.FindRoom();
room.addClient(client);

This room (parent) now has a client (child).

client.on('message', (event) => {
   // With the above code, room must be found
   let room = rooms.FindClientsRoom(client);
   if(room){
       room.handleMessage(event);
   }
});

Or we have a child that knows about its parent

let client = new Client();
let room = rooms.FindRoom();
room.addClient(client);
client.setRoom(room);


client.on('message', (event) => {
   let room = client.getRoom();
   if(room){
       room.handleMessage(event);
   }
});

This is incredibly fast compared to looking for a client within 1000s of rooms. But is there something wrong with the design pattern? In any system, such as XML, do child nodes know about their parents? Should they?

Go to Source
Author: de-playable

Timer refresh page in a function

In my function I have a page refresh at the end to actually update the table, however the refresh is faster than the database.

Anyone have an idea how I can change this?

echo '<script>                                                                          ';
echo 'function updateId(id) {                                                             ';
echo 'var xmlhttp = new XMLHttpRequest();                                               ';
echo '    xmlhttp.onreadystatechange = function() {                                     ';
echo '        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)                     ';
echo '        {                                                                         ';
//echo '            alert(xmlhttp.responseText);                                          ';
echo '        }                                                                         ';
echo '    };                                                                            ';
echo '    xmlhttp.open("GET", "update.php?id=" +id, true);                              ';
echo '    xmlhttp.send();                                                               ';
echo 'location.reload(true);                                                                ';

echo '}                                                                                 ';
echo '</script>                                                                         ';
?>

Go to Source
Author: Tjerk Peters

How can I add a custom Javascript snippet to display my feedback in footer?

I have the following Javascript snippet:

<script type="text/javascript" src="<script type="text/javascript" src="//www.auctionnudge.com/feed/feedback/js/theme/profile_table/limit/6/lang/english/UserID/stockmustgo/siteid/3"></script><div id="auction-nudge-feedback" class="auction-nudge"></div>

Which should dynamically display my eBay feedback like this:

https://gyazo.com/1ddc1e3f2ca21c91897a986a01654df8

How can I add this to my wordpress site? I tried installing the ‘ Header and Footer Scripts ‘ plugin to no avail. I’m sure it’s simple but I’m a beginner when it comes to anything web dev related.

It doesn’t need to be displayed in the footer. It can be within the body. I’ve asked around and I couldn’t find anyone that could help so I thought I’d try here. Thanks.

Go to Source
Author: Chrome123

page alignment and div element alignment

So I am trying to build a page like this :

enter image description here

but it looks like this:
enter image description here

I try to use multiple div and also combine Row and Col to do it but it seems a mess. Some changes also do not have any effects.

Code:


import React from 'react';
import TextContents from '../assets/translations/TextContents';
import BlueButton from '../components/materialdesign/BlueButton';
import TeachIcon from '../assets/images/teach-class-icon.svg';
import HostIcon from '../assets/images/host-a-class-icon.svg';

import './CreateClassAndHost.css';
import { Row, Col } from 'react-bootstrap';

class CreateClassAndHost extends React.Component {

    render() {

        const CreateAClass = 
            <Col className="create-tile">
                <div className="create-style-title">
                    <img
                        src= { TeachIcon }
                        className= "create-icon"
                        alt="TeachIcon"
                    />    
                    <h2>{TextContents.BeATeacher}</h2>
                </div>
                <p>{TextContents.BeATeacherDesc}</p>
                <div className="create-button">
                <BlueButton textSize="13" link_href="/createaclass" text={TextContents.BeATeacherBtn} />
                </div>
            </Col>;

        const CreateAHost = 
            <Col className="create-tile">
                <div className="create-style-title">
                    <img
                        src= { HostIcon }
                        className= "create-icon"
                        alt="HostIcon"
                    />  
                    <h2>{TextContents.HostAClass}</h2>
                </div>
                <p>{TextContents.HostAClassDesc}</p>
                <div className="create-button">
                <BlueButton textSize="13" link_href="/createahost" text={TextContents.HostAClassBtn} />
                </div>
            </Col>;
        return (
            <div className="create-container">
                <h1>{TextContents.CreateClassOrHostTitle}</h1>
                <Row classname="create-section">
                    {CreateAClass}
                    {CreateAHost}
                </Row>
            </div>

        );
    }

}

export default CreateClassAndHost;

Css code :

.create-container {
    width: 80%;
    position: absolute;
    display: flex;
    text-align: center;
    margin-top:5%;
    margin-bottom: 5%;
}

.create-container h1 {
    text-align: center;
    height: 51px;
    margin: auto;
    font-family: Fredoka One;
    font-size: 50px;
    color: #333333;
    width:100%;
}

.create-section {
    width:100%;
}

.create-icon {
    width:47px;
    height:47px ;
}

.create-style-title {

}

.create-tile {
    display: inline-block;
    left: 12px;
    top: 80px;
    text-align: center;
    width: 200px;
    height: 250px;
    background-color: #ffffff;
}


.create-tile h2 {
    font-family: Source Sans Pro;
    font-weight: bold;
    font-size: 30px;
    line-height: 0.7;
    color: #333333;
    letter-spacing: -0.6px;

}

.create-tile p {
    font-family: Source Sans Pro;
    font-size: 20px;
    line-height: 1.6;
    color: #616161;
    width: 280px;
    height: 85px; 
}

.create-button {
    position: relative;
    left: 0px;
    top: 50px;
}

Any idea how to make it looks like the page provide above ?

Also anyone can provide a good resources on how to build properly layout. I would like to also looke at myself on some resource easily showing how to align,.. build…

Thanks

Go to Source
Author: Seb

validationRegex to accept/validate listed characters

5 to 16 alpha or alphanumeric to include special characters such as:
◦*Hyphen ( – )
◦*Slash ( / )
◦*Backslash ( )
◦*Asterisk ( * )
◦*Dollar Sign ( $ )
◦*Period ( . )
◦*Ampersand ( & )
◦*Comma ( , )
◦*Number Sign ( # )
◦*Open Parenthesis ( ( )
◦*Closed Parenthesis ( ) )
◦*Colon ( : )

Current code example:

PASSWORD: {id: password, label: PASSWORD, name: PASSWORD, validationRegex: ^[a-zA-Z0-9]+$, minLength: 5, maxLength: 16, errorMsg: message}

Go to Source
Author: Marcus