How to run a button’s click event using just a keyboard shortcut instead of actually clicking

DevTools screenshot

I want to run the “share” action right away via keyboard shortcut, skipping the clicking. Is this possible?

Normally, what I do is

  1. Using AHK, click the top right share button.

  2. Wait a second for the “share chat” dialog.

  3. Then click the share (I want to run this action right away via keyboard shortcut)

function sK() {} <— this is the function that shows on all the button events; different actions, such as “new chat” and “share,” use the same function.

// ==UserScript==
// @name         TEST GLOBAL: DETECT KEY (ALT + K)
// @match        *://*/*
// ==/UserScript==

(function() {
    'use strict'

    document.addEventListener('keydown', function(event) {
        if (event.altKey && event.key === 'k') { // alt + key
            let SHARE_BUTTON = document.querySelector(".bg-text-000")

            // ---------- I COULD DO THIS, BUT THIS IS NOT WHAT I WANT ----------
            let TOP_RIGHT_SHARE_BUTTON = document.querySelector("#top-right-button")
            TOP_RIGHT_SHARE_BUTTON.click()
        }
    })
})()

Resolving CORS Error in Python Stock Analyzer

I’ve been working on this stock analysis and prediction web application (python backend, JS/React frontend) and I keep getting “Cross-Origin Request Blocked” when I have it try to calculate indicators. Backend code below, any assistance is appreciated.

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
import yfinance as yf
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
from ta.trend import SMAIndicator, MACD
from ta.momentum import RSIIndicator
from ta.volatility import BollingerBands

app = FastAPI(title="Stock Analysis and Prediction Platform")

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["*"]
)

class StockRequest(BaseModel):
    symbol: str
    period: str = "1y"

class PredictionRequest(BaseModel):
    symbol: str
    features: List[str]
    target: str
    days_ahead: int = 5
    model_type: str

@app.get("/")
async def root():
    return {"message": "Welcome to Stock Analysis and Prediction API"}

@app.post("/stock/historical")
async def get_historical_data(request: StockRequest):
    try:
        # Get historical data
        stock = yf.Ticker(request.symbol)
        df = stock.history(period=request.period)
        
        if df.empty:
            raise HTTPException(status_code=404, detail=f"No data found for symbol {request.symbol}")
        
        # Convert DataFrame to list of dictionaries
        df.index = df.index.strftime('%Y-%m-%d')
        return df.reset_index().to_dict('records')
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/stock/indicators")
async def calculate_indicators(request: StockRequest):
    try:
        # Get historical data
        stock = yf.Ticker(request.symbol)
        df = stock.history(period=request.period)
        
        if df.empty:
            raise HTTPException(status_code=404, detail=f"No data found for symbol {request.symbol}")
        
        # Calculate indicators
        # RSI
        rsi = RSIIndicator(close=df['Close'], window=14)
        df['RSI'] = rsi.rsi()
        
        # MACD
        macd = MACD(close=df['Close'])
        df['MACD'] = macd.macd()
        
        # Bollinger Bands
        bollinger = BollingerBands(close=df['Close'])
        df['BB_high'] = bollinger.bollinger_hband()
        df['BB_low'] = bollinger.bollinger_lband()
        
        # Convert DataFrame to list of dictionaries
        df.index = df.index.strftime('%Y-%m-%d')
        return df.reset_index().to_dict('records')
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/stock/predict")
async def predict_stock(request: PredictionRequest):
    try:
        # Get historical data
        stock = yf.Ticker(request.symbol)
        df = stock.history(period="2y")
        
        if df.empty:
            raise HTTPException(status_code=404, detail=f"No data found for symbol {request.symbol}")
        
        # Prepare features
        for feature in request.features:
            if feature not in df.columns:
                raise HTTPException(status_code=400, detail=f"Feature {feature} not found")
        
        X = df[request.features].values
        y = df[request.target].values
        
        # Split data
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
        
        # Train model
        if request.model_type == "linear":
            model = LinearRegression()
        elif request.model_type == "random_forest":
            model = RandomForestRegressor(n_estimators=100, random_state=42)
        else:
            raise HTTPException(status_code=400, detail="Unsupported model type")
        
        model.fit(X_train, y_train)
        y_pred = model.predict(X_test)
        
        # Calculate metrics
        mse = mean_squared_error(y_test, y_pred)
        r2 = r2_score(y_test, y_pred)
        
        # Predict next n days
        last_data = df[request.features].values[-1:]
        future_pred = model.predict(last_data)
        
        return {
            "current_price": float(df['Close'].iloc[-1]),
            "predicted_price": float(future_pred[0]),
            "mse": float(mse),
            "r2": float(r2),
            "days_ahead": request.days_ahead
        }
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000) 

I expected it to calculate technical indicators (RSI, Bollinger bands, etc.), but I get “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/stock/indicators. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 500.”

Angular Memory Management

I am trying to understand if there is an easy way to unsubscribe automatically from observables/subjects.

For example, lets say I have a component

@Component({
   selector: 'mySelector',
   template: `<div>Hello World</div>`,
   styleUrls: [ 'myStyles.scss' ]
})
export class MyComponent {
   constructor(private service: MyService){ }
   ngOnInit()
   {
      /// Forgot to store subscription!!!!!!!!!!!!!!!
      this.service.clickStream$.subscribe( clickEvent => {
         DoSomething();
      } );
   }

   DoSomething()
   {
      console.log('DoSomething');
   }

}
      

Here the developer has forgotten to store the subscription or call unsubscribe on the subscription. Ideally, should have stored the subscription and called subscription.unsubscribe() in the ngOnDestroy.

In C++, we have smartpointers like shared_ptr/auto_ptr. Is there anything similar in Angular/Typescript that automatically unsubscribes in case a developer forgets.

Authenticate to Google Language API using API Key for REST based web app

I am receiving an error 401 when trying to authenticate to Google API using an API Key.

The following is the javascript code used to make the call:

function test()
{
        const outputElement = document.getElementById('output');

        const apiUrl = 'https://translation.googleapis.com/language/translate/v2';

        const requestOptions = {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer APIKEYINSERTEDHERE',
                'x-goog-user-project': 'projectname',
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: {
                'q': 'the house is built with wood',
                'target': 'fr-CA'
            },
        };

        fetch(apiUrl, requestOptions)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                outputElement.textContent = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

Same results happen when using postman:
URL: https://translation.googleapis.com/language/translate/v2
Method: POST

Query Params:
q=the house is built with wood
target=fr-CA

Headers
x-goog-user-project: projectname
Authorization: Bearer APIKEYINSERTEDHERE
Content-Type: application/json; charset=utf-8

Response
{
“error”: {
“code”: 401,
“message”: “Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.”,
“errors”: [
{
“message”: “Invalid Credentials”,
“domain”: “global”,
“reason”: “authError”,
“location”: “Authorization”,
“locationType”: “header”
}
],
“status”: “UNAUTHENTICATED”,
“details”: [
{
“@type”: “type.googleapis.com/google.rpc.ErrorInfo”,
“reason”: “ACCESS_TOKEN_TYPE_UNSUPPORTED”,
“metadata”: {
“method”: “google.cloud.translate.v2.TranslateService.TranslateText”,
“service”: “translate.googleapis.com”
}
}
]
}
}

Appreciate any insights anyone has why I can’t make a basic request using the API key for authentication.

Various authentication methods.
Read the documentation. Debugged using POSTMAN
The error messages keep changing.

ENOENT: no such file or directory, open ‘E:Projectsreact_practiceNext-Projectchat-apptestdata5-versions-space.pdf’

While parsing the pdf in nextjs 15 javascript, I’m having an this error, ENOENT: no such file or directory, open ‘E:Projectsreact_practiceNext-Projectchat-apptestdata5-versions-space.pdf’

API –

import { NextResponse } from "next/server"
import pdfParse from 'pdf-parse'

export const POST = async (req) => {
    try {
        const formData = await req.formData()
        const file = formData.get('file')
        
        if (!file) {
            return NextResponse.json({ error: 'No file uploaded' }, { status: 400 });
          }
        
          const buffer = Buffer.from(await file.arrayBuffer());
          const data = await pdfParse(buffer);
        
          return NextResponse.json({ text: data.text }, { status: 200 });
    } catch (error) {
        console.error('PDF processing error:', error)
        return NextResponse.json({ message: 'PDF processing failed' }, { status: 500 })
    }
}

Page.jsx –

const handleUpload = async (file) => {
    const formData = new FormData();
    formData.append('file', file);
  
    const response = await fetch('/api/convert', {
      method: 'POST',
      body: formData,
    });
  
    const data = await response.json();
    console.log(data.text);
  };

conflict mmenu.js and Google CSE

I use mmenu and want to implement the Google search engine.
All works fine, except that some results show “Close submenu”, then some keywords that are nowhere to be found in the source code of that page, and then again “Close submenu”. In other search results it shows “Open submenu”.

So in mmenu.js I adjusted this line of code:

    text:{closeMenu:"Close menu",closeSubmenu:"Close submenu",openSubmenu:"Open submenu",toggleSubmenu:"Toggle submenu"}

into

    text:{closeMenu:"",closeSubmenu:"",openSubmenu:"",toggleSubmenu:""}

but it still shows in the search results.

Did anyone else encounter this issue, and how to make sure it doesn’t appear?

Javascript Obfuscator and Decryption [closed]

I have a set of sequential APIs to crack.
I did manage to crack the initial ones, but I am stuck at the last stage.
Please check the json file here:
https://drive.google.com/file/d/11eL5RGz4LyHhPk45Ki_r_hGs8JNpzDOd/view?usp=sharing

Here is the code after De-Obfuscation:
https://drive.google.com/file/d/13hIAll0QN3ZFoD8LM3ifIvFPqBlSZOz2/view?usp=sharing

I am not sure about the encryption used for the text after the eval function.
Someone please decrypt it for me or at least tell me how to separate and decrypt using different methods.

HTML form not submitting

I am trying to make a login form in html. But, when I click submit, the JavaScript code doesn’t execute. Here is my JavaScript/jquery code:

$('#login').submit(function(e) {
    e.preventDefault();
    alert('test');
    $('#submit_login').prop('dissabled', true);
    $('span[id$="error"] ').html('').css('desplay', 'none');
    $('#form_message').html('').css('desplay', 'none');
    
    //get the form data
    formData = $(this).serializeArray();
    $.post('handlers/user_handler.php', formData, function(data) {
        let result = JSON.parse(data);
        if(result.status === 'error') {
            $('#' + result.control + '_error').html(result.message).css('desplay', 'inline-block');
        } else {
            window.location = 'http://localhost/Official%20Lasereyes%20Website/public/index.php';
        }
    });
});

Here is my html:

    <form id='login'>
<div class='form_wrapper'>
<div class='control_wrapper'>
<lable for='username'>Email:</lable><br>
<input type='email' id='username' class='form_control' name='username' aria-lable='Type your email address' autocomplete='username' required><br>
<span id='Username_error' class='error error_message'></span>
</div>
<div class='control_wrapper'>
<lable for='password'>Password:</lable><br>
<input id='password' name='password' type='password' minlength='8' aria-lable='Type your password.' autocomplete='current-password' required><br>
<input type='checkbox' id='password_toggle'><lable for='password_toggle' class='lable_horizontal'>Show Password</lable>
</div>
<span id='password_error' class='error error_message'></span>
</div>
<button id='submit_login' class='btn btn_form' type='submit'>Login</button>
<span id='form_error' class='error error_message form_error'></span>
<span id='form_message' class='form_message'></span>
<input type='hidden' id='user_verb' name='user_verb' value='login'>
<input type='hidden' id='token' name='token' value='<?php echo $_SESSION['token']; ?>'>
</div>
</form>

Even stranger, the data from the form appears in a query string apereas in the URL. The PHP login function ran, but the JavaScript that sent the code to PHP didn’t. Can someone help me with this?
query string

Supabase : Migrate storage objects

I tried to run this script from supabase to migrate storage objects.
The goal is to copy storage objects from one project to another project.

https://supabase.com/docs/guides/platform/migrating-within-supabase/backup-restore#migrate-storage-objects

// npm install @supabase/supabase-js@1
const { createClient } = require('@supabase/supabase-js')
const OLD_PROJECT_URL = 'https://xxx.supabase.co'
const OLD_PROJECT_SERVICE_KEY = 'old-project-service-key-xxx'
const NEW_PROJECT_URL = 'https://yyy.supabase.co'
const NEW_PROJECT_SERVICE_KEY = 'new-project-service-key-yyy'
;(async () => {
  const oldSupabaseRestClient = createClient(OLD_PROJECT_URL, OLD_PROJECT_SERVICE_KEY, {
    db: {
      schema: 'storage',
    },
  })
  const oldSupabaseClient = createClient(OLD_PROJECT_URL, OLD_PROJECT_SERVICE_KEY)
  const newSupabaseClient = createClient(NEW_PROJECT_URL, NEW_PROJECT_SERVICE_KEY)
  // make sure you update max_rows in postgrest settings if you have a lot of objects
  // or paginate here
  const { data: oldObjects, error } = await oldSupabaseRestClient.from('objects').select()
  if (error) {
    console.log('error getting objects from old bucket')
    throw error
  }
  for (const objectData of oldObjects) {
    console.log(`moving ${objectData.id}`)
    try {
      const { data, error: downloadObjectError } = await oldSupabaseClient.storage
        .from(objectData.bucket_id)
        .download(objectData.name)
      if (downloadObjectError) {
        throw downloadObjectError
      }
      const { _, error: uploadObjectError } = await newSupabaseClient.storage
        .from(objectData.bucket_id)
        .upload(objectData.name, data, {
          upsert: true,
          contentType: objectData.metadata.mimetype,
          cacheControl: objectData.metadata.cacheControl,
        })
      if (uploadObjectError) {
        throw uploadObjectError
      }
    } catch (err) {
      console.log('error moving ', objectData)
      console.log(err)
    }
  }
})()

But I get this error:

error getting objects from old bucket
node:internal/process/promises:389
      new UnhandledPromiseRejection(reason);
      ^

UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<Object>".
    at throwUnhandledRejectionsMode (node:internal/process/promises:389:7)
    at processPromiseRejections (node:internal/process/promises:470:17)
    at process.processTicksAndRejections (node:internal/process/task_queues:96:32) {
  code: 'ERR_UNHANDLED_REJECTION'
}

JavaScript – synchronous execution of code

I tried to demonstrate to someone how JavaScript executes code synchronously, and it didn’t work the way I expected. So I’m trying to figure out why my little snippet didn’t do what I expected it to do.

The example I put together was this:

console.log('First line of code');
for (let i = 0; i < 10000000000; i++) {
    let j = i + i;
}
console.log('Last line of code');

I figured the first console log would execute, then the for loop would execute, creating a pause (can’t use setTimeout for pause since it is asynchronous), and then the second console log would execute. I put the pause in because any simple code I put together would appear to execute simultaneously.

What actually happened when I executed it was that the pause occurred first, then both console logs appeared simultaneously.

Just to make sure I wasn’t going crazy, I did the two console logs again, but with a for loop of 0 through 10 that printed a console log for each iteration. That went as expected – first console log, then the console logs for the for loop, then the second console log.

For my first example, why the heck didn’t the first console log print out before the for loop executed? Why did it not print out until after the for loop appeared finished?

Emotion Css, new is getting outputted in the almost every time when i click on component’s style

Emotion Css, new <style> is getting outputted in the <head> almost every time when I click on component. For example when I click on a button I have a ripple effect, where the ripple starts from where the user clicks. If I change the location where the user is clicking every time a new style tag gets added. Is there any optimisation I can do to avoid this?

<style data-emotion="css" data-s="">
  .css-ed674j-ripple_effect {
    -webkit-transform: scale(0);
    -moz-transform: scale(0);
    -ms-transform: scale(0);
    transform: scale(0);
    border-radius: 100%;
    position: absolute;
    -webkit-animation-name: animation-h7qd33;
    animation-name: animation-h7qd33;
    -webkit-animation-duration: 850ms;
    animation-duration: 850ms;
    opacity: 0.75;
    background-color: var(--color-accent-100);
    top: -59.296875px;
    left: 36px;
    width: 169.59375px;
    height: 169.59375px;
  }
</style>

<style data-emotion="css" data-s="">
  @-webkit-keyframes animation-h7qd33 {
    to {
      opacity: 0;
      -webkit-transform: scale(2);
      -moz-transform: scale(2);
      -ms-transform: scale(2);
      transform: scale(2);
    }
  }
</style>

<style data-emotion="css" data-s="">
  @keyframes animation-h7qd33 {
    to {
      opacity: 0;
      -webkit-transform: scale(2);
      -moz-transform: scale(2);
      -ms-transform: scale(2);
      transform: scale(2);
    }
  }
</style>

enter image description here

Override keepalive timeout AWS ingress controller

I am running a Aws EKS cluster with Load balancer and Ingress Controller. When I call an API in NodeJs service which I am running as pod in EKS cluster its returning 499 error. When The API call takes below 60 seconds its returning data but when its above 60 seconds its errors out with status code 499.

I have override service, ingress keepalive-timeout, loadbalancer timeout to 600 seconds

LoadBalancer Data

{
    "LoadBalancerAttributes": {
        "CrossZoneLoadBalancing": {
            "Enabled": false
        },
        "AccessLog": {
            "Enabled": false
        },
        "ConnectionDraining": {
            "Enabled": true,
            "Timeout": 600
        },
        "ConnectionSettings": {
            "IdleTimeout": 600
        },
        "AdditionalAttributes": [
            {
                "Key": "elb.http.desyncmitigationmode",
                "Value": "defensive"
            }
        ]
    }
}

Ingress Controller Data

worker_shutdown_timeout 240s ;
        keepalive_timeout  75s;
        client_header_timeout           600s;
        client_body_timeout             600s;
        ssl_session_timeout 10m;
                keepalive_timeout  60s;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             600;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             600;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                        proxy_connect_timeout                   600s;
                        proxy_send_timeout                      600s;
                        proxy_read_timeout                      600s;
                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_timeout             0;
                keepalive_timeout 0;

I noted that ingress have 3 keepalive_timeout but only top I can override.

what is the solution to extend the API call to wait beyond 1 minute(60 seconds)?

Drag and Drop Elements Independently in Vanilla JS

I’m new to Javascript, but getting close to finishing the vanilla JS for a mock desktop UI project: opening asides as “windows” that can be reordered, selected, and moved independently anywhere on the page. (I’m building a blog that mimics a desktop.)

I’m having trouble on that last part: getting my drag & drop functions to target one aside at a time. I have three asides that I want to drag, drop, then fix to the page while other asides are moved. The first drag & drop often works, but subsequent moves will capture and move all of the other open “windows” together.

Here is my project Fiddle: https://jsfiddle.net/kze09617/#&togetherjs=dd5Ez1bMHO
To open windows, click the toggle buttons.

I think the issue might be in how I’ve ordered or layered my functions; I’m brand new to JS, but am trying to learn the ropes by reinventing wheels.

I have set a function to add the class “.active” (which adds position: absolute and transform: translateZ(10) to each aside onclick) and remove it from the others:

function bringForward(elem) {
    var windows = document.querySelectorAll("aside");
    for (i = 0; i < windows.length; i++) {
        windows[i].classList.remove('active');
        windows[i].style.draggable === "false"
        windows[i].style.position === "fixed";
    }
elem.classList.add('active');
elem.style.draggable === "true";
elem.style.position === "absolute";
}

And set event listeners, so if a window is clicked again, it will allow drag & drop. Attempting to prevent my collective moving issue, I separated each drag & drop function by window, but it didn’t work. This makes me think the issue could be in the drag & drop functions themselves:

 windowOne.addEventListener('click', function() {
     
    if (windowOne.classList.contains('active')) {
    function dragStart (e) {
        var style = window.getComputedStyle(e.target, null);
        e.dataTransfer.setData("text/plain", 
            (parseInt(style.getPropertyValue("left"), 10) - e.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - e.clientY));
    
    }
    
    function dragOver (e) {
        e.preventDefault();
        return false;
    }
    
    function dropDown (e) {
        var offset = e.dataTransfer.getData("text/plain").split(',');
        var dm = document.getElementById('window1');
        dm.style.left = (e.clientX + parseInt(offset[0],10)) + 'px';
        dm.style.top = (e.clientY + parseInt(offset[1],10)) + 'px';
        e.preventDefault();
        return false;
    }
    
    var dm = document.getElementById('window1');
    dm.addEventListener('dragstart', dragStart, false);
    document.body.addEventListener('dragover', dragOver, false);
    document.body.addEventListener('drop', dropDown, false);
    }
    else {
        windowOne.classList.add('active'); 
        }
    
    })


windowTwo.addEventListener('click', function() {
 
    if (windowTwo.classList.contains('active')) {
function dragStart2 (e) {
    var style = window.getComputedStyle(e.target, null);
    e.dataTransfer.setData("text/plain", 
        (parseInt(style.getPropertyValue("left"), 10) - e.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - e.clientY));

}

function dragOver2 (e) {
    e.preventDefault();
    return false;
}

function dropDown2 (e) {
    var offset2 = e.dataTransfer.getData("text/plain").split(',');
    var dm2 = document.getElementById('window2');
    dm2.style.left = (e.clientX + parseInt(offset2[0],10)) + 'px';
    dm2.style.top = (e.clientY + parseInt(offset2[1],10)) + 'px';
    e.preventDefault();
    return false;
}

var dm2 = document.getElementById('window2');
dm2.addEventListener('dragstart', dragStart2, false);
document.body.addEventListener('dragover', dragOver2, false);
document.body.addEventListener('drop', dropDown2, false);
}
else {
    windowTwo.classList.add('active'); 
    }

})


windowThree.addEventListener('click', function() {
 
    if (windowThree.classList.contains('active')) {
function dragStart3 (e) {
    var style = window.getComputedStyle(e.target, null);
    e.dataTransfer.setData("text/plain", 
        (parseInt(style.getPropertyValue("left"), 10) - e.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - e.clientY));

}

function dragOver3 (e) {
    e.preventDefault();
    return false;
}

function dropDown3 (e) {
    var offset3 = e.dataTransfer.getData("text/plain").split(',');
    var dm3 = document.getElementById('window3');
    dm3.style.left = (e.clientX + parseInt(offset3[0],10)) + 'px';
    dm3.style.top = (e.clientY + parseInt(offset3[1],10)) + 'px';
    e.preventDefault();
    return false;
}

var dm3 = document.getElementById('window3');
dm3.addEventListener('dragstart', dragStart3, false);
document.body.addEventListener('dragover', dragOver3, false);
document.body.addEventListener('drop', dropDown3, false);

}
else {
    windowThree.classList.add('active'); 
    }

})

Any advice is appreciated – I really hope I can make this work.