Posts in Website Development

How to Get Value of ViewBag in JavaScript: A Beginner’s Guide ⚡

Hey there, fellow coder! Ever been scratching your head wondering how to pull data from your server-side ViewBag into your client-side JavaScript? Trust me, you’re not alone. Today, we’re going to break down how to get the value of ViewBag in JavaScript in a clear, step-by-step way—all while keeping it fun and approachable.


What’s the Deal with ViewBag? 🤔

If you’re working with ASP.NET MVC (or ASP.NET Core MVC), you already know that ViewBag is a dynamic property that lets you pass data from your controller to your view. But here’s the twist: when you need that data on the client side (i.e., in JavaScript), you have to bridge the gap between server-side code and your browser. Think of it as teleporting a message from one world to another!


Method 1: Inline JavaScript with Razor Syntax

The simplest way to get a ViewBag value into JavaScript is to directly embed it in your script block using Razor. Here’s a quick example:

<!-- In your Razor view (e.g., Index.cshtml) -->
@{
ViewBag.Message = "Hello, World!";
}
<script>
// Access the ViewBag value using Razor syntax.
var message = '@ViewBag.Message';
alert(message); // Displays: Hello, World!
</script>

Why this works:
When the server processes the Razor view, it replaces @ViewBag.Message with its actual value. The resulting JavaScript code then becomes something like:

javascriptCopyEditvar message = 'Hello, World!';

Simple, right? 😊


Method 2: Using JSON Serialization for Complex Data

Sometimes, your ViewBag might hold more than just a simple string. If you’re dealing with objects or arrays, it’s best to use JSON serialization. This method ensures that the data is formatted correctly for JavaScript.

@{
// Let's assume ViewBag.User holds an object with Name and Age.
ViewBag.User = new { Name = "Alice", Age = 30 };
}
<script>
// Use JSON serialization to safely pass complex data.
var user = @Html.Raw(Json.Encode(ViewBag.User));
console.log("User Name: " + user.Name); // Outputs: Alice
console.log("User Age: " + user.Age); // Outputs: 30
</script>

Pro Tip:
Using Html.Raw(Json.Encode(...)) prevents any issues with quotes and special characters. It’s like wrapping your data in a neat, secure package before sending it off.


Method 3: Hidden Input Field – The Sneaky Way

If you prefer not to clutter your JavaScript with inline code, you can also store the ViewBag value in a hidden input field and then grab it using JavaScript.

@{
ViewBag.Info = "Secret info!";
}
<!-- Hidden input field holding the ViewBag value -->
<input type="hidden" id="viewbagInfo" value="@ViewBag.Info" />

<script>
// Retrieve the value from the hidden field.
var info = document.getElementById("viewbagInfo").value;
console.log("ViewBag Info: " + info); // Outputs: Secret info!
</script>

This method is especially handy when you have several pieces of data to pass around without mixing them into your main script.


Things to Keep in Mind ⚠️

  • Server vs. Client:
    Remember, ViewBag is evaluated on the server. By the time your JavaScript runs, the ViewBag value is already rendered into your HTML.
  • Data Types:
    When dealing with non-string data, always lean towards JSON serialization to keep your data intact and free from formatting issues.
  • Security First:
    Be cautious about what data you expose on the client side. Don’t pass sensitive information through ViewBag unless absolutely necessary.

Final Thoughts 🎉

Accessing the value of ViewBag in JavaScript is a powerful way to bridge your server-side logic with your client-side interactivity. Whether you’re using inline Razor, JSON serialization, or a hidden field, the key is to pick the method that best suits your project’s needs.

So go ahead, experiment with these techniques, and add a little extra magic to your web applications. If you found this guide helpful or have any cool tricks of your own, drop a comment below or check out more tips on SharihHassan.com. Happy coding! 🚀

How to Add a Glow Effect to Images in HTML & CSS ✨ | Image Glow HTML

Ever wanted to make your images pop? Maybe give them a neon glow effect that makes your website look straight out of a sci-fi movie? 🚀 Well, today, I’ll show you how to achieve that glow effect in HTML and CSS. It’s super simple and requires just a few lines of code.


1️⃣ Basic Glow Effect with CSS

In HTML, images are added using the <img> tag, but the magic happens in CSS. To create a glow effect, we use the box-shadow property.

📌 Example Code: Basic Image Glow Effect

htmlCopyEdit<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Glow Effect</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #222;
        }

        img {
            width: 300px;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 255, 255, 0.8); /* Cyan glow effect */
            transition: 0.3s;
        }

        img:hover {
            box-shadow: 0 0 40px rgba(0, 255, 255, 1); /* Stronger glow on hover */
        }
    </style>
</head>
<body>
    <img src="your-image.jpg" alt="Glowing Image">
</body>
</html>

🛠️ What’s Happening Here?

  • box-shadow: 0 0 20px rgba(0, 255, 255, 0.8); → Adds a soft cyan glow.
  • transition: 0.3s; → Smooth animation when hovering.
  • img:hover → Increases glow intensity on hover.

Try replacing rgba(0, 255, 255, 0.8) with other colors like rgba(255, 0, 0, 0.8) for a red glow or rgba(0, 255, 0, 0.8) for a green glow. 🎨


2️⃣ Advanced Glow Effect with CSS Filters

Want an even cooler effect? Use the filter property!

📌 Example Code: Advanced Glow Effect

cssCopyEditimg {
    filter: drop-shadow(0 0 20px cyan);
}

💡 Why Use drop-shadow Instead of box-shadow?

  • drop-shadow keeps the glow around the actual shape of the image (great for transparent PNGs).
  • box-shadow applies a glow around the entire rectangular box.

3️⃣ Animated Glowing Effect (Breathing Glow) 🌟

What if the glow effect pulses like it’s alive? Add CSS animations!

📌 Example Code: Pulsing Glow Effect

cssCopyEdit@keyframes glow {
    0% { box-shadow: 0 0 10px cyan; }
    50% { box-shadow: 0 0 30px cyan; }
    100% { box-shadow: 0 0 10px cyan; }
}

img {
    animation: glow 2s infinite alternate;
}

This will make the image pulse with a glowing aura—perfect for gaming websites, neon themes, or just making your site look cool. 🎮


4️⃣ SEO Benefits of Using Glow Effects on Images

Alright, let’s talk SEO. 🔍 While CSS effects don’t directly impact rankings, engagement and user experience do. A glowing image can:

Grab Attention – Visitors stay longer, reducing bounce rate.
Improve Click-Through Rate (CTR) – Eye-catching visuals increase interactions.
Enhance Readability & UI/UX – A well-designed site means better retention.
Boost Social Shares – Cool effects encourage people to share your content.

📌 Pro Tip: Always use alt tags (alt="Glowing Image") for accessibility and SEO! Google loves it when you describe your images properly.


Final Thoughts

And that’s it! Now you know how to create a glowing image effect in HTML using box-shadow, drop-shadow, and even animations. 🌟 Whether it’s for a portfolio, blog, or e-commerce website, adding these subtle effects can enhance your design without affecting performance.

Here You can read my Previous Blog: How to Webscrape Images from HTML: A Developer’s Guide (Without Getting Blocked 🚫)

🔥 Now, go and make your images glow like a neon sign in the dark! Let me know if you try this effect. 🚀

CSS Code for Auto-Adjust to Screen Size: The Ultimate Guide to Responsive Design (No Yoga Mat Required)

Hey, Sharih Hassan here! 👋 You asked, I deliver: a deep-dive guide on CSS that auto-adjusts to every screen size. We’re talking mobile, tablet, desktop, and even your grandma’s ancient iPad. Let’s turn “Why does this look weird?” into “Holy guacamole, it’s perfect!” 🥑

(Pssst… If you’re new to CSS customization, warm up with my Squarespace CSS Injection Guide—it’s like stretching before a marathon.)


Why Bother with Auto-Adjusting CSS?

Let’s get real: 55% of web traffic is mobile, and Google ranks responsive sites higher. Your site isn’t just a pretty face—it’s a survivalist. Think of this guide as your website’s personal trainer. 💪


Step 1: The Mobile-First Mindset (Start Small, Scale Up)

Why it matters: Mobile-first isn’t a trend—it’s a strategy. Design for tiny screens first, then add complexity for larger ones. Your CSS will be cleaner, and your users happier.

Code Example: Mobile-First Hero Section

CSS

/* Default (mobile) styles */  
.hero {  
  padding: 20px;  
  text-align: center;  
}  
.hero-title {  
  font-size: 1.8rem; /* Big enough for thumbs */  
}  

/* Tablet tweaks */  
@media (min-width: 768px) {  
  .hero {  
    padding: 40px;  
  }  
  .hero-title {  
    font-size: 2.5rem;  
  }  
}  

/* Desktop drama */  
@media (min-width: 1024px) {  
  .hero {  
    display: flex;  
    align-items: center;  
    justify-content: space-between;  
    padding: 60px;  
  }  
  .hero-title {  
    font-size: 3.5rem;  
  }  
}  

Pro Tip: Use rem instead of px for scalable typography.


Step 2: Fluid Layouts (Goodbye Rigid, Hello Flexible)

The problem: Fixed widths (width: 500px;) explode on small screens.
The fix: Use percentages, max-width, and min-width to create elastic containers.

Code Example: A Fluid Grid That Adapts Like a Champ

CSS

.container {  
  width: 90%;  
  max-width: 1200px; /* Prevents IMAX syndrome on desktops */  
  margin: 0 auto;  
}  

.card {  
  width: 100%; /* Fills container on mobile */  
  min-width: 250px; /* Won’t shrink past this */  
  margin: 10px;  
}  

@media (min-width: 768px) {  
  .card {  
    width: calc(50% - 20px); /* 2 columns, accounting for margin */  
  }  
}  

@media (min-width: 1024px) {  
  .card {  
    width: calc(33.33% - 20px); /* 3 columns */  
  }  
}  

Step 3: Media Queries Demystified (Breakpoints That Don’t Break You)

Breakpoints 101: These are screen sizes where your design “adapts.” Common ones:

  • 320px (Small phones)
  • 480px (Large phones)
  • 768px (Tablets)
  • 1024px (Small desktops)
  • 1200px+ (Big screens)

Code Example: Responsive Navigation Menu

CSS

/* Mobile: Stack links vertically */  
.nav-link {  
  display: block;  
  padding: 10px;  
}  

/* Tablet: Horizontal menu */  
@media (min-width: 768px) {  
  .nav-link {  
    display: inline-block;  
    padding: 15px 20px;  
  }  
}  

/* Desktop: Add fancy hover effects */  
@media (min-width: 1024px) {  
  .nav-link {  
    position: relative;  
  }  
  .nav-link:hover::after {  
    content: "";  
    position: absolute;  
    bottom: 0;  
    left: 0;  
    width: 100%;  
    height: 3px;  
    background: #ff6b6b;  
  }  
}  

Step 4: Flexbox vs. Grid (Choose Your Weapon)

Flexbox: Perfect for 1D layouts (rows or columns).
Grid: For 2D layouts (rows and columns).

Flexbox Example: A Responsive Testimonial Section

CSS

.testimonials {  
  display: flex;  
  flex-direction: column; /* Stack on mobile */  
  gap: 20px;  
}  

@media (min-width: 768px) {  
  .testimonials {  
    flex-direction: row; /* Side-by-side on larger screens */  
    flex-wrap: wrap; /* Allows wrapping if space runs out */  
  }  
  .testimonial {  
    flex: 1 1 300px; /* Grow, shrink, minimum width */  
  }  
}  

Grid Example: A Gallery That Auto-Fits

CSS

.gallery {  
  display: grid;  
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));  
  gap: 15px;  
}  

/* Bonus: Add hover zoom */  
.gallery img {  
  transition: transform 0.3s;  
}  
.gallery img:hover {  
  transform: scale(1.03);  
}  

Step 5: Images & Videos That Behave (No More Overflow!)

The golden rule: Always prevent media from breaking layouts.

CSS

img, video, iframe {  
  max-width: 100%; /* Never exceed container width */  
  height: auto; /* Maintain aspect ratio */  
}  

/* For background images */  
.hero {  
  background-image: url("your-image.jpg");  
  background-size: cover; /* Fills container without stretching */  
  background-position: center;  
}  

Step 6: Test Like a Mad Scientist 🔬

Tools to save your sanity:

  1. Chrome DevTools: Emulate devices with Ctrl+Shift+I → Toggle Device Toolbar.
  2. Responsive Design Checker: Test on 50+ devices at once (responsivedesignchecker.com).
  3. Real Devices: Borrow your friend’s phone. Bribe them with coffee if needed. ☕

Common Pitfalls (And How to Dodge Them)

  1. Overusing !important: It’s the CSS equivalent of yelling. Use semantic HTML instead.
  2. Ignoring touch targets: Buttons smaller than 48px? Mobile users will curse you.
  3. Forgetting landscape mode: Test horizontal layouts on phones too!

Conclusion: Responsive Design = Happy Users (and Google)

Auto-adjusting CSS isn’t just about looking good—it’s about being accessible to everyone, everywhere. Whether you’re coding a portfolio, e-commerce site, or a blog, these principles ensure your site flexes without breaking a sweat.


Want more CSS sorcery? 🧙♂️ Check out my Squarespace CSS Injection Guide to unlock even more design superpowers.

Now go forth and make the internet a little less janky. 🚀

Cheers,
Sharih Hassan
(The developer who debugged this article on 3 different screens) 📱💻🖥️

How to Webscrape Images from HTML: A Developer’s Guide (Without Getting Blocked 🚫)

Hey folks! 👋 Sharih Hassan back at it again—your code-cracking buddy from SharihHassan.com. Last time, we tackled how to prevent Angular from returning HTML when you wanted JSON. Today? We’re going rogue: how to webscrape images from HTML without ending up on a website’s naughty list. Buckle up, and let’s do this ethically (and hilariously).


Why Webscrape Images? (And Why It’s Like Walking a Tightrope 🎪)

Webscraping images is like sneaking cookies from the cookie jar 🍪—everyone does it, but you gotta be smooth. Maybe you’re building a meme archive, training an AI, or just really into cat pictures 🐈. But scrape carelessly, and you’ll get blocked faster than a pop-up ad in 2005.


Step 1: Inspect the HTML—Be a Detective 🕵️♀️

Right-click any webpage, hit “Inspect,” and you’ll see HTML tags laughing at you. Images usually live inside <img> tags with src attributes. Your mission? Extract those src URLs like a pro.

html

<!-- Example: A very serious cat image -->  
<img src="https://website.com/cat-in-a-suit.jpg" alt="Business Cat">  

Run HTML


Step 2: Use JavaScript (But Don’t Be a Script Kiddie)

For static sites, Cheerio (a lightweight jQuery-like library) is your BFF. For dynamic sites, Puppeteer (a headless browser) will pretend to be a human. Here’s a sneak attack:

JavaScript

// Puppeteer example: Scrape images like a ninja  
const puppeteer = require('puppeteer');  

(async () => {  
  const browser = await puppeteer.launch();  
  const page = await browser.newPage();  
  await page.goto('https://example.com');  

  const images = await page.$$eval('img', imgs =>  
    imgs.map(img => img.src)  
  );  

  console.log("🕶️ Here’s your loot:", images);  
  await browser.close();  
})();  

Pro Tip: Always check a site’s robots.txt first. Ignoring it is like ignoring a “Beware of Dog” sign 🐕.


Step 3: Filter & Download Responsibly 🌱

Not all images are created equal. Filter out logos, icons, or anything with alt="annoying-ad". Use Node.js’s fs module or Python’s requests to download them.

JavaScript

// Filter only high-res cat pics (priorities, people)  
const catImages = images.filter(src =>  
  src.includes('cat') && !src.includes('thumbnail')  
);  

Step 4: Avoid Getting Blocked (AKA Don’t Be a Greedy Goblin)

Websites hate scrapers that hit them 100 times/second. Add delays, rotate user agents, and use proxies. Or just… don’t be a bot 🤖.

JavaScript

// Puppeteer with a polite delay  
await page.waitForTimeout(3000); // 3 seconds = good karma  

Step 5: Ethical Stuff (Because We’re Not Villains)

  • Respect copyrights: Don’t scrape Unsplash and sell the pics as NFTs.
  • Credit creators: If you use ’em, link back.
  • Rate limits: Treat websites like a buffet—take one plate at a time.

Final Thoughts: Scrape Smart, Not Hard 💡

Webscraping images is powerful, but with great power comes great “why is my IP banned?” energy. Use tools wisely, respect website rules, and maybe leave a virtual thank-you note 💌.

And hey, if you’re still wrestling with HTML in Angular, revisit my guide on preventing HTML responses in Angular. Because nobody wants JSON dressed as HTML!

Got scraping horror stories? Share ’em on the blog! Catch you in the next post.
Sharih Hassan ✌️

Authorization Bearer session_id in JavaScript: Secure User Sessions Made Simple

Hey there, fellow devs! 👋 I’m Sharih Hassan, and if you’ve ever lost sleep over authentication bugs, you’re in good company. Today, we’re diving into authorization bearer session_id in JavaScript—a critical (but often misunderstood) part of securing user sessions. By the end of this guide, you’ll handle tokens like a pro, and I’ll even tie this to a fun trick I shared earlier about simulating keyboard typing in the JavaScript console. Let’s get started!


What’s a Bearer Token? (And Why You Need One)

Imagine you’re at a theme park 🎢. You buy a ticket, get a wristband, and boom—you can ride all day. A bearer token is that wristband. It’s a string (like session_id) your server generates when a user logs in. Attach it to requests, and the server says, “Ah, I remember you! Come on in.”

In JavaScript, you send this token in the Authorization header:

JavaScript

fetch('https://api.your-app.com/profile', {
  headers: {
    'Authorization': 'Bearer YOUR_SESSION_ID' // Your golden ticket 🎫
  }
});

If the token is invalid or missing? The server throws a 401 Unauthorized error. No rides for imposters!


session_id: The Secret Sauce for Remembering Users

Without session_id, your server treats users like strangers after every request. Awkward, right? Here’s how it works:

  1. User Logs In: The server creates a unique session_id, stores it (e.g., in a database), and sends it to the client.
  2. Client Saves It: Store session_id securely—localStorage for simplicity, or HTTP-only cookies for added security.
  3. Token in Action: Attach the session_id to future requests via the Authorization: Bearer header.

It’s like whispering, “Pssst, server—it’s me again!” every time you fetch data.


Step-by-Step Code Implementation

1. Handling User Login

When users submit credentials, your server validates them and issues a session_id:

JavaScript

async function loginUser(email, password) {
  const response = await fetch('/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password }),
  });

  if (!response.ok) {
    throw new Error('Login failed! ❌'); // Handle errors gracefully
  }

  const { session_id } = await response.json();
  localStorage.setItem('session_id', session_id); // Store securely
}

2. Attaching the Token to Requests

For authenticated routes, include the session_id in the header:

JavaScript

async function fetchProtectedData() {
  const session_id = localStorage.getItem('session_id');

  if (!session_id) {
    throw new Error('No session_id found. Redirect to login! ⚠️');
  }

  const response = await fetch('/api/protected-data', {
    headers: {
      Authorization: `Bearer ${session_id}` // The server checks this 🕵️
    }
  });

  return response.json();
}

3. Handling Token Expiration

Tokens shouldn’t last forever. Set an expiration time and refresh them when needed:

JavaScript

// Server-side example (Node.js)
const generateSessionId = () => {
  return {
    token: crypto.randomBytes(32).toString('hex'),
    expiresIn: Date.now() + 3600 * 1000 // 1 hour expiry ⏳
  };
};

On the client side, check expiration and prompt re-login or refresh tokens.


Security Best Practices

  • Use HTTPS: Always. Tokens sent over HTTP are like postcards—anyone can read them. 🔒
  • HTTP-Only Cookies: Store session_id in cookies with httpOnly and secure flags to prevent XSS attacks.
  • Short Expiry Times: Limit token lifespan to reduce damage if leaked.
  • Avoid LocalStorage for Sensitive Apps: It’s accessible via JavaScript, making it vulnerable to XSS.

Testing and Debugging: Simulate Auth Flows

Remember my guide on simulating keyboard typing in the JavaScript console? That’s a game-changer for testing login forms! Automate input to trigger session_id generation faster:

JavaScript

// Simulate typing into a login form (from previous article)
function simulateLogin(email, password) {
  const emailField = document.querySelector('#email');
  const passwordField = document.querySelector('#password');
  
  // Simulate keystrokes
  simulateKeyInput(emailField, email); // Check my earlier tutorial for this!
  simulateKeyInput(passwordField, password);
  
  document.querySelector('#login-btn').click(); // Trigger login
}

This helps test token generation without manual typing. Debugging made fun! 🚀


Common Mistakes to Avoid

  1. Tokens in URLs: Never pass session_id in URLs—it can leak in logs or browser history.
  2. Hardcoding Tokens: Avoid embedding tokens in client-side code. Always fetch them dynamically.
  3. Ignoring Server-Side Validation: Validate tokens on the server every time. Don’t trust the client!

Why This All Matters

  • User Trust: Secure sessions mean fewer breaches and happier users.
  • Scalability: Stateless tokens reduce server load. No database checks for every request!
  • Compliance: Many regulations (like GDPR) require secure authentication practices.

Wrapping Up: Tokens, Sessions, and a Little Automation Magic

Mastering authorization bearer session_id in JavaScript isn’t just about code—it’s about building trust with users. Pair this with tools like simulating keyboard inputs for seamless testing, and you’ll save time while keeping security tight.

Recap:

  1. Generate session_id on login.
  2. Attach it via Authorization: Bearer headers.
  3. Store securely, expire wisely, and validate always.

Got questions or horror stories about auth? Share them below! 👇 And for more JavaScript tricks, visit my blog at SharihHassan.com.

Happy coding—and may your tokens never leak! 🔑

Squarespace CSS Injection: Spice Up Your Site Like a Pro (Without Breaking It) 🚀

Hey there, fellow developer! 👋 It’s Sharih Hassan back at it again, ready to crack open the ~magic~ of Squarespace CSS injection. You know, Squarespace is like that friend who gives you a perfectly baked pizza base—great on its own, but oh boy, it’s the toppings (read: custom CSS) that make it legendary. Let’s turn your “meh” template into a “WOW” masterpiece. 🍕✨


Why CSS Injection? (Spoiler: Control Freaks Rejoice)

Squarespace’s built-in design tools are fine, but let’s be real—sometimes you need to yell, “I AM THE DESIGNER NOW” 💻⚡. CSS injection lets you override default styles, fix weird mobile layouts, or even add animations that make visitors do a double-tap. Ready to play god with your website’s aesthetics? Let’s go.


Step 1: Find the Secret CSS Portal

First, navigate to your Squarespace dashboard:
Design → Custom CSS.

This is your sandbox. Your playground. Your CSS Batcave. 🦇 Pro tip: Always back up your site before going wild here (trust me, future-you will high-five present-you).


CSS Injection Examples: Let’s Get Dangerous

1. Button Glow-Ups (Because Flat Buttons Are So 2010)

Want a button that screams “CLICK ME OR ELSE”?

CSS

.sqs-block-button-element {  
  background: linear-gradient(90deg, #ff6b6b, #ff8e8e);  
  border-radius: 50px !important;  
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);  
  transition: transform 0.3s ease;  
}  

.sqs-block-button-element:hover {  
  transform: scale(1.05);  
  background: linear-gradient(90deg, #ff8e8e, #ff6b6b);  
}  

What this does: Adds a gradient, bounce effect, and shadow to buttons. Perfect for making CTAs pop!


2. Murder the Default Font (RIP, Arial)

Tired of Squarespace’s font choices? Time to kidnap the typography.

CSS

h1, h2, h3 {  
  font-family: 'Poppins', sans-serif !important;  
  letter-spacing: -0.03em;  
}  

body {  
  font-family: 'Inter', sans-serif !important;  
}  

Don’t forget: Add the Google Font link via Design → Custom CSS → Manage Custom Files!


3. Image Hover Sorcery 🔮

Make images zoom or fade on hover (because drama):

CSS

.sqs-image-content img {  
  transition: all 0.5s ease;  
}  

.sqs-image-content img:hover {  
  transform: scale(1.03);  
  opacity: 0.9;  
}  

4. Fix Mobile Layouts (Because Squarespace Mobile Sometimes Forgets)

Is your mobile view looking like a toddler stacked the blocks? Fix it with:

CSS

@media screen and (max-width: 640px) {  
  .page-section {  
    padding-top: 20px !important;  
    padding-bottom: 20px !important;  
  }  
}  

The Golden Rule: How to Not Break Your Site

  • Test in stages: Deploy one CSS tweak at a time.
  • Use Inspector Tools: Right-click → Inspect Element to find classes/IDs.
  • !important is your frenemy: Use sparingly, or you’ll start a CSS civil war.

Conclusion: Your Site, Your Rules

CSS injection turns Squarespace from a templated platform into your personal design laboratory. 🧪 Whether you’re tweaking buttons, fonts, or layouts, remember: with great power comes great responsibility (and maybe a few broken layouts along the way).


Want more CSS wizardry? 🧙♂️ Check out my previous guide: Mastering CSS Color Export in Squarespace—it’s the rainbow to your storm! 🌈

Now go forth and inject responsibly. 💉✨

Cheers,
Sharih Hassan
(The developer who’s 50% coffee, 50% CSS) ☕️💻

How to Prevent Returning HTML in Angular: A Developer’s Guide (Without Losing Your Sanity 😱)

Hey there, fellow coders! 👋 Sharih Hassan here—your friendly neighborhood developer and blogger at SharihHassan.com. Today, we’re tackling a quirky little problem that’s haunted many Angular devs: how to stop your app from returning HTML when you specifically asked for JSON. Let’s turn that frustration into action—and maybe share a laugh along the way.


Wait, Why Am I Getting HTML Instead of Data? 🤔

Picture this: You’re happily coding an Angular app, sipping coffee ☕, and suddenly your API call returns… an entire HTML page instead of that sweet, sweet JSON. It’s like ordering a latte and getting a cactus 🌵. Not cool.

This usually happens when:

  • Your API endpoint is misconfigured (oops).
  • The server throws an error (like a 404 or 500) and dumps HTML instead of JSON.
  • You’ve accidentally called the wrong URL (been there, done that 💁♂️).

But fear not! Let’s fix this faster than you can say, “Why is my app rendering a 404 page?!”


Step 1: Check Your Endpoints (No, Seriously)

First, channel your inner detective 🕵️♂️. Did you typo the API URL? Check your environment.ts file or wherever you store endpoints. A misplaced / can turn your data fetch into a wild goose chase.

Typescript

// environment.ts  
export const environment = {  
  production: false,  
  apiUrl: 'https://your-api.com/data' // Not 'https://your-api.com/data/' 🙅♂️  
};  

Pro tip: Use Angular’s HttpClient with error handling to catch these gremlins early:

Typescript

getData() {  
  return this.http.get(environment.apiUrl).pipe(  
    catchError((error) => {  
      console.log("Hey, why is there HTML here?! 🔍", error);  
      throw error;  
    })  
  );  
}  

Step 2: Forcefully Reject HTML Responses

Sometimes, servers get too helpful and return HTML even on errors. To avoid this, explicitly ask for JSON in your HTTP headers:

Typescript

getData() {  
  const headers = new HttpHeaders({  
    'Accept': 'application/json' // "I said JSON, please!" 📢  
  });  
  return this.http.get(environment.apiUrl, { headers });  
}  

If the server still sends HTML, it’s time to yell at your backend team. Politely, of course. 😇


Step 3: Validate Responses Like a Bouncer 🚧

Don’t trust strangers—even your API. Use Angular’s interceptors to validate responses before they wreak havoc:

Typescript

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
  return next.handle(req).pipe(  
    filter(event => event instanceof HttpResponse),  
    map((event: HttpResponse<any>) => {  
      if (event.headers.get('Content-Type')?.includes('text/html')) {  
        throw new Error('HTML detected! Abort! Abort! 🚨');  
      }  
      return event;  
    })  
  );  
}  

Now your app will block HTML at the door like an overzealous nightclub bouncer.


Step 4: Handle Errors Gracefully (Because Stuff Happens)

Even with precautions, errors happen. Maybe the server is down, or a cat walked on the keyboard 🐱💻. Use Angular’s error handling to show friendly messages instead of raw HTML:

Typescript

this.dataService.getData().subscribe({  
  next: (data) => this.showData(data),  
  error: (err) => {  
    this.displayError("Oops! Our hamsters took a break. 🐹 Try again later!");  
  }  
});  

Step 5: Server-Side Fixes (Because Teamwork Makes the Dream Work)

If you control the backend, ensure it never returns HTML for API routes. For example, in Node.js/Express:

Javascript

app.use('/api', (req, res, next) => {  
  res.status(404).json({ error: 'Not Found' }); // Not res.sendFile('404.html')!  
});  

Final Thoughts: Keep Calm and Code On 💪

Returning HTML instead of JSON is like getting socks for Christmas—unexpected and mildly infuriating. But with proper error handling, headers, and teamwork, you’ll squash this bug faster than you can say, “Where’s my data?!”

By the way, if you’re into quirky JavaScript hacks, check out my previous article on How to Simulate Keyboard Typing in the JavaScript Console. It’s a fun little trick that’ll make you feel like a coding wizard 🧙‍♂️.

Catch you in the next post!
– Sharih Hassan ✌️

How to Simulate Keyboard Typing in the JavaScript Console: A Beginner-Friendly Guide ⌨️

Have you ever wanted to simulate keyboard typing in the JavaScript console for debugging, automation, or just for fun? Well, you’re in the right place! Today, we’ll walk through how to achieve this using JavaScript step by step. By the end of this article, you’ll be able to create a typing effect directly in your browser’s console. Let’s get started! 🚀


Why Simulate Keyboard Typing in the Console? 🔎

Simulating typing in the console can be useful for:

  • Debugging and Testing: Automating input scenarios.
  • Demonstrations: Showcasing a typing effect during a tutorial or presentation.
  • Entertainment: Adding a fun typing animation to impress your friends or colleagues.

The Basics: What You Need to Know ✨

Before diving into the code, let’s cover some key concepts:

  1. The console.log() Method:
    • This is how you display messages in the browser console.
  2. JavaScript setTimeout and setInterval:
    • These functions allow you to delay or repeat actions over time, which is perfect for creating a typing effect.
  3. String Manipulation:
    • We’ll need to break a string into individual characters to simulate typing.

JavaScript Simulate Keyboard Typing in Console – Step-by-Step🔧

Here’s how to create a simple typing simulation using JavaScript:

1. Define the Text to Simulate

Start by creating the message you want to type out:

const message = "Hello, world! This is a simulated typing effect.";

2. Set Up a Typing Function

Next, create a function that will handle the typing effect:

function simulateTyping(text, delay = 100) {
    let index = 0;

    const interval = setInterval(() => {
        if (index < text.length) {
            console.log(text[index]);
            index++;
        } else {
            clearInterval(interval);
        }
    }, delay);
}

3. Call the Function

Call the simulateTyping function and pass in your message and delay:

simulateTyping(message, 200); // Types out each character every 200ms

Output:

Open your browser console (usually by pressing F12 or Ctrl+Shift+I), and you’ll see each character of the message appear one by one.


Advanced: Adding a Cursor Effect 🔍

For an even more realistic typing effect, you can include a blinking cursor:

function simulateTypingWithCursor(text, delay = 100) {
    let index = 0;
    let cursor = "|";

    const interval = setInterval(() => {
        if (index < text.length) {
            console.clear();
            console.log(text.slice(0, index + 1) + cursor);
            index++;
        } else {
            clearInterval(interval);
            console.clear();
            console.log(text); // Final text without cursor
        }
    }, delay);
}

simulateTypingWithCursor(message, 150);

Output:

The text will appear in the console, and a blinking cursor will follow the typed characters until the message is complete.


Pro Tips 💡

  1. Adjust Speed:
    • Play with the delay parameter to control typing speed.
  2. Handle Multiple Lines:
    • Use \n to simulate typing on a new line. For example:const message = "Hello, world!\nThis is line two.";
  3. Combine with DOM Manipulation:
    • You can use similar logic to simulate typing on a web page instead of the console.

Conclusion 🎉

Simulating keyboard typing in the JavaScript console is not only a fun experiment but also a handy tool for demos, debugging, and automation. Whether you’re testing key events or simulating user input in an input field, mastering this technique can add a touch of interactivity to your projects.

Got more JavaScript tricks up your sleeve? Share them in the comments or check out more tutorials on SharihHassan.com. Happy coding! 🎮

Mastering CSS Color Export: From Figma, Sketch, and Generators to Your Codebase 🖌️

Designers and developers often face the challenge of translating beautiful color palettes from design tools into clean, reusable CSS code. Whether you’re using Figma, Sketch, or an online color generator, exporting colors into CSS doesn’t have to be complicated. Today, we’ll break down the process of exporting color styles and show you how to make the transition seamless. Let’s dive in! 🌊


Why Exporting Colors to CSS Matters 🌟

Consistency is key in web development. By exporting color styles directly from design tools like Figma or Sketch, you:

  • Save time by avoiding manual color copying.
  • Ensure design and development teams stay on the same page.
  • Maintain a consistent color scheme across your project.

Exporting Color Styles from Figma to CSS 🖋

Figma is a powerhouse for designers, and exporting colors to CSS is straightforward. Here’s how:

  1. Set Up Color Styles in Figma:
    • Select an element with the desired color.
    • Click the Style icon in the right-hand panel and choose Create Style.
    • Name your color style (e.g., Primary, Secondary, Accent).
  2. Copy CSS from Figma:
    • Select the element.
    • Go to the Inspect tab (on the right).
    • Scroll to the CSS section, where you’ll see the color properties (e.g., background-color: #FF5733;).
  3. Paste into Your Stylesheet:
    • Open your CSS file and paste the copied color code under the relevant class or ID:.primary { background-color: #FF5733; }

Pro Tip: Use Variables 🛠️

To make your color palette reusable, define them as CSS variables:

:root {
    --primary-color: #FF5733;
    --secondary-color: #33FF57;
}

Exporting Colors from Sketch to CSS 🎨

Sketch is another favorite among designers. Here’s how to get your colors into CSS:

  1. Create Color Presets:
    • Open the Color Picker and add your colors to the Document Colors.
  2. Use Plugins for Exporting:
    • Install a plugin like Sketch2React or Sketch Measure.
    • Use the plugin to export your color palette as a CSS file.
  3. Manual Copy:
    • Similar to Figma, you can manually inspect an element and copy its color properties.

Using Color Generators to Export CSS 💨

Sometimes, you might use an online color generator for inspiration. Here’s how to export CSS from popular tools:

  1. Coolors.co:
    • Generate your palette.
    • Click Export and select CSS.
    • Copy the CSS variables and paste them into your stylesheet.
    Example output::root { --color1: #264653; --color2: #2A9D8F; --color3: #E9C46A; }
  2. Adobe Color:
    • Create your palette and select Export.
    • Download the CSS file or copy the code directly.

Tips for Managing Color Styles Efficiently 🚀

  • Name Colors Logically: Instead of naming colors by their appearance (e.g., Blue1, Blue2), use functional names like Primary, Background, or Accent.
  • Centralize Colors: Keep your color variables in one file (e.g., colors.css) to make updates easy.
  • Use Preprocessors: If you’re using Sass or LESS, you can use variables to manage colors dynamically.

Final Thoughts 🌐

Exporting colors from Figma, Sketch, or a color generator to CSS doesn’t have to be a headache. With a little organization and the right tools, you can ensure your color schemes remain consistent and developer-friendly.

Got a favorite tool or tip for managing colors? Share it in the comments or explore more tips on SharihHassan.com for better design-to-code workflows. Happy coding! 🚀

HTML Form Creation Made Easy: How to View Results Using JavaScript 👨🏻‍💻

Forms are the backbone of user interaction on the web. Whether it’s signing up for a newsletter, logging in, or collecting feedback, forms do the heavy lifting. But let’s face it—creating an HTML form and figuring out how to display the results might feel intimidating at first. Fear not! 😊 By the end of this guide, you’ll know how to create a basic HTML form and view its results using JavaScript. Let’s get started!


Step 1: Creating the HTML Form 🏛️

First, let’s create a simple form. This form will ask for a user’s name and email and include a submit button. Here’s what the HTML code looks like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Form Example</title>
</head>
<body>
    <h1>Sign Up Form</h1>
    <form id="signupForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br><br>

        <button type="submit">Submit</button>
    </form>

    <div id="result" style="margin-top: 20px;"></div>
</body>
</html>

Key Points:

  • <form>: The container for all input fields.
  • <input>: Used to collect data (e.g., text, email).
  • required: Ensures users don’t leave fields blank.
  • id: Helps JavaScript identify and manipulate specific elements.

Step 2: Using JavaScript to View Form Results 🎨

Now that we have our form, let’s use JavaScript to display the results when the user submits the form.

Add the following JavaScript code inside a <script> tag at the end of the HTML file:

<script>
    // Select the form element
    const form = document.getElementById('signupForm');

    // Add an event listener for form submission
    form.addEventListener('submit', function(event) {
        // Prevent the default form submission behavior
        event.preventDefault();

        // Get the values from the input fields
        const name = document.getElementById('name').value;
        const email = document.getElementById('email').value;

        // Display the results
        const resultDiv = document.getElementById('result');
        resultDiv.innerHTML = `<p><strong>Name:</strong> ${name}</p><p><strong>Email:</strong> ${email}</p>`;
    });
</script>

What’s Happening Here?

  1. Prevent Default Behavior: The event.preventDefault() method stops the form from reloading the page upon submission.
  2. Retrieve Input Values: The .value property gets the user’s input from the fields.
  3. Display Results: We update the innerHTML of the <div> element to show the name and email.

Step 3: Test It Out! 🎮

Save your HTML file and open it in a browser. Fill out the form, hit “Submit,” and watch as the results appear instantly below the form. No page reloads. No confusion. Just magic! 🎩


Why Use JavaScript for This? 🚀

JavaScript makes forms interactive and dynamic. Here are some benefits:

  • Instant Feedback: Users see results immediately without reloading the page.
  • Validation: You can validate inputs (e.g., checking if an email is valid).
  • Flexibility: JavaScript lets you enhance the form’s functionality over time.

Bonus: Adding Some Style 🎨

Want your form to look as good as it works? Add this simple CSS to style it:

<style>
    body {
        font-family: Arial, sans-serif;
        margin: 20px;
    }
    form {
        max-width: 300px;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 8px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    input {
        width: 100%;
        padding: 10px;
        margin-bottom: 10px;
        border: 1px solid #ccc;
        border-radius: 4px;
    }
    button {
        background-color: #007BFF;
        color: white;
        padding: 10px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    button:hover {
        background-color: #0056b3;
    }
</style>

Now your form not only works like a charm but also looks modern and sleek.


Final Thoughts 🌟

Creating HTML forms and displaying their results using JavaScript is a vital skill for any web developer. It’s the first step toward building interactive, user-friendly web applications.

If you found this helpful, check out more practical guides on SharihHassan.com and start building your web development skills today!

Happy coding! 🌐