Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
State Design Pattern
Next article icon

Observer Design Pattern

Last Updated : 05 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Observer Design Pattern is a behavioral design pattern that defines a one-to-many dependency between objects. When one object (the subject) changes state, all its dependents (observers) are notified and updated automatically.

observers

Table of Content

  • What is the Observer Design Pattern?
  • Real-world analogy of the Observer Design Pattern
  • Components of Observer Design Pattern
  • Observer Design Pattern Example
  • When to use the Observer Design Pattern?
  • When not to use the Observer Design Pattern?

What is the Observer Design Pattern?

The Observer Design Pattern is a behavioral design pattern that defines a one-to-many dependency between objects. When one object (the subject) changes state, all its dependents (observers) are notified and updated automatically. It primarily deals with the interaction and communication between objects, specifically focusing on how objects behave in response to changes in the state of other objects.

Note: Subjects are the objects that maintain and notify observers about changes in their state, while Observers are the entities that react to those changes.

Below are some key points about observer design pattern:

  • Defines how a group of objects (observers) interact based on changes in the state of a subject.
  • Observers react to changes in the subject's state.
  • The subject doesn't need to know the specific classes of its observers, allowing for flexibility.
  • Observers can be easily added or removed without affecting the subject.

Real-world analogy of the Observer Design Pattern

Let's understand the observer design pattern through a real-world example:

Imagine a scenario where a weather station is observed by various smart devices. The weather station maintains a list of registered devices. Weather Station will update all the devices whenever there is change in the weather.

  • Each of the devices are concrete observers and each have their ways to interpret and display the information.
  • The Observer Design Pattern provides a flexible and scalable system where adding new devices or weather stations doesn't disrupt the overall communication, providing real-time and location-specific weather updates to users.

Components of Observer Design Pattern

Below are the main components of Observer Design Pattern:

Observer-(1)

  • Subject:
    • The subject maintains a list of observers (subscribers or listeners).
    • It Provides methods to register and unregister observers dynamically and defines a method to notify observers of changes in its state.
  • Observer:
    • Observer defines an interface with an update method that concrete observers must implement and ensures a common or consistent way for concrete observers to receive updates from the subject.
  • ConcreteSubject:
    • ConcreteSubjects are specific implementations of the subject. They hold the actual state or data that observers want to track. When this state changes, concrete subjects notify their observers.
    • For instance, if a weather station is the subject, specific weather stations in different locations would be concrete subjects.
  • ConcreteObserver:
    • Concrete Observer implements the observer interface. They register with a concrete subject and react when notified of a state change.
    • When the subject's state changes, the concrete observer's update() method is invoked, allowing it to take appropriate actions.
    • For example, a weather app on your smartphone is a concrete observer that reacts to changes from a weather station.

Observer Design Pattern Example

To understand observer design pattern, lets take an example:

Consider a scenario where you have a weather monitoring system. Different parts of your application need to be updated when the weather conditions change.

Challenges or difficulties while implementing this system without Observer Design Pattern

  • Components interested in weather updates would need direct references to the weather monitoring system, leading to tight coupling.
  • Adding or removing components that react to weather changes requires modifying the core weather monitoring system code, making it hard to maintain.

How Observer Pattern helps to solve above challenges?

The Observer Pattern facilitates the decoupling of the weather monitoring system from the components that are interested in weather updates (via interfaces). Every element can sign up as an observer, and observers are informed when the weather conditions change. The weather monitoring system is thus unaffected by the addition or removal of components.

ObserverPatternExample

Below is the code of above problem statement using Observer Pattern:

1. Subject

  • The "Subject" interface outlines the operations a subject (like "WeatherStation") should support.
  • "addObserver" and "removeObserver" are for managing the list of observers.
  • "notifyObservers" is for informing observers about changes.
Java
public interface Subject {
    void addObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers();
}

2. Observer

  • The "Observer" interface defines a contract for objects that want to be notified about changes in the subject ("WeatherStation" in this case).
  • It includes a method "update" that concrete observers must implement to receive and handle updates.
Java
public interface Observer {
    void update(String weather);
}

3. ConcreteSubject(WeatherStation)

  • "WeatherStation" is the concrete subject implementing the "Subject" interface.
  • It maintains a list of observers ("observers") and provides methods to manage this list.
  • "notifyObservers" iterates through the observers and calls their "update" method, passing the current weather.
  • "setWeather" method updates the weather and notifies observers of the change.
Java
import java.util.ArrayList;
import java.util.List;

public class WeatherStation implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String weather;

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(weather);
        }
    }

    public void setWeather(String newWeather) {
        this.weather = newWeather;
        notifyObservers();
    }
}

4. ConcreteObserver(PhoneDisplay)

  • "PhoneDisplay" is a concrete observer implementing the "Observer" interface.
  • It has a private field weather to store the latest weather.
  • The "update" method sets the new weather and calls the "display" method.
  • "display" prints the updated weather to the console.
Java
public class PhoneDisplay implements Observer {
    private String weather;

    @Override
    public void update(String weather) {
        this.weather = weather;
        display();
    }

    private void display() {
        System.out.println("Phone Display: Weather updated - " + weather);
    }
}

5. ConcreteObserver(TVDisplay)

  • "TVDisplay" is another concrete observer similar to "PhoneDisplay".
  • It also implements the "Observer" interface, with a similar structure to "PhoneDisplay".
Java
class TVDisplay implements Observer {
    private String weather;
 
    @Override
    public void update(String weather) {
        this.weather = weather;
        display();
    }
 
    private void display() {
        System.out.println("TV Display: Weather updated - " + weather);
    }
}

6. Usage

  • In "WeatherApp", a "WeatherStation" is created.
  • Two observers ("PhoneDisplay" and "TVDisplay") are registered with the weather station using "addObserver".
  • The "setWeather" method simulates a weather change to "Sunny," triggering the "update" method in both observers.
  • The output shows how both concrete observers display the updated weather information.
Java
public class WeatherApp {
    public static void main(String[] args) {
        WeatherStation weatherStation = new WeatherStation();

        Observer phoneDisplay = new PhoneDisplay();
        Observer tvDisplay = new TVDisplay();

        weatherStation.addObserver(phoneDisplay);
        weatherStation.addObserver(tvDisplay);

        // Simulating weather change
        weatherStation.setWeather("Sunny");

        // Output:
        // Phone Display: Weather updated - Sunny
        // TV Display: Weather updated - Sunny
    }
}

Complete code for the above example

Below is the complete code for the above example:

Java
import java.util.ArrayList;
import java.util.List;

// Observer Interface
interface Observer {
    void update(String weather);
}

// Subject Interface
interface Subject {
    void addObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers();
}

// ConcreteSubject Class
class WeatherStation implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String weather;

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(weather);
        }
    }

    public void setWeather(String newWeather) {
        this.weather = newWeather;
        notifyObservers();
    }
}

// ConcreteObserver Class
class PhoneDisplay implements Observer {
    private String weather;

    @Override
    public void update(String weather) {
        this.weather = weather;
        display();
    }

    private void display() {
        System.out.println("Phone Display: Weather updated - " + weather);
    }
}

// ConcreteObserver Class
class TVDisplay implements Observer {
    private String weather;

    @Override
    public void update(String weather) {
        this.weather = weather;
        display();
    }

    private void display() {
        System.out.println("TV Display: Weather updated - " + weather);
    }
}

// Usage Class
public class WeatherApp {
    public static void main(String[] args) {
        WeatherStation weatherStation = new WeatherStation();

        Observer phoneDisplay = new PhoneDisplay();
        Observer tvDisplay = new TVDisplay();

        weatherStation.addObserver(phoneDisplay);
        weatherStation.addObserver(tvDisplay);

        // Simulating weather change
        weatherStation.setWeather("Sunny");

        // Output:
        // Phone Display: Weather updated - Sunny
        // TV Display: Weather updated - Sunny
    }
}
Output
Phone Display: Weather updated - Sunny
TV Display: Weather updated - Sunny

When to use the Observer Design Pattern?

Below is when to use observer design pattern:

  • When you need one object to notify multiple others about changes.
  • When you want to keep objects loosely connected, so they don’t rely on each other’s details.
  • When you want observers to automatically respond to changes in the subject’s state.
  • When you want to easily add or remove observers without changing the main subject.
  • When you’re dealing with event systems that require various components to react without direct connections.

When not to use the Observer Design Pattern?

Below is when not to use observer design pattern:

  • When the relationships between objects are simple and don’t require notifications.
  • When performance is a concern, as many observers can lead to overhead during updates.
  • When the subject and observers are tightly coupled, as it defeats the purpose of decoupling.
  • When number of observers is fixed and won’t change over time.
  • When the order of notifications is crucial, as observers may be notified in an unpredictable sequence.

Next Article
State Design Pattern

S

Sulabh Kumar
Improve
Article Tags :
  • Design Pattern
  • System Design

Similar Reads

  • Software Design Patterns Tutorial
    Software design patterns are important tools developers, providing proven solutions to common problems encountered during software development. This article will act as tutorial to help you understand the concept of design patterns. Developers can create more robust, maintainable, and scalable softw
    9 min read
  • Complete Guide to Design Patterns
    Design patterns help in addressing the recurring issues in software design and provide a shared vocabulary for developers to communicate and collaborate effectively. They have been documented and refined over time by experienced developers and software architects. Important Topics for Guide to Desig
    11 min read
  • Types of Software Design Patterns
    Designing object-oriented software is hard, and designing reusable object-oriented software is even harder. Christopher Alexander says, "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way th
    9 min read
  • 1. Creational Design Patterns

    • Creational Design Patterns
      Creational Design Patterns focus on the process of object creation or problems related to object creation. They help in making a system independent of how its objects are created, composed, and represented. Creational patterns give a lot of flexibility in what gets created, who creates it, and how i
      4 min read
    • Types of Creational Patterns

      • Factory method Design Pattern
        The Factory Method Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass, allowing subclasses to alter the type of objects that will be created. This pattern is particularly useful when the exact types of objects to be created may vary or need
        7 min read

      • Abstract Factory Pattern
        The Abstract Factory Pattern is one of the creational design patterns that provides an interface for creating families of related or dependent objects without specifying their concrete classes and implementation, in simpler terms the Abstract Factory Pattern is a way of organizing how you create gro
        8 min read

      • Singleton Method Design Pattern in JavaScript
        Singleton Method or Singleton Design Pattern is a part of the Gang of Four design pattern and it is categorized under creational design patterns. It is one of the most simple design patterns in terms of modeling but on the other hand, this is one of the most controversial patterns in terms of comple
        9 min read

      • Singleton Method Design Pattern
        The Singleton Method Design Pattern ensures a class has only one instance and provides a global access point to it. It’s ideal for scenarios requiring centralized control, like managing database connections or configuration settings. This article explores its principles, benefits, drawbacks, and bes
        11 min read

      • Prototype Design Pattern
        The Prototype Design Pattern is a creational pattern that enables the creation of new objects by copying an existing object. Prototype allows us to hide the complexity of making new instances from the client. The existing object acts as a prototype and contains the state of the object. Table of Cont
        8 min read

      • Builder Design Pattern
        The Builder Design Pattern is a creational pattern used in software design to construct a complex object step by step. It allows the construction of a product in a step-by-step manner, where the construction process can change based on the type of product being built. This pattern separates the cons
        9 min read

      2. Structural Design Patterns

      • Structural Design Patterns
        Structural Design Patterns are solutions in software design that focus on how classes and objects are organized to form larger, functional structures. These patterns help developers simplify relationships between objects, making code more efficient, flexible, and easy to maintain. By using structura
        7 min read
      • Types of Structural Patterns

        • Adapter Design Pattern
          One structural design pattern that enables the usage of an existing class's interface as an additional interface is the adapter design pattern. To make two incompatible interfaces function together, it serves as a bridge. This pattern involves a single class, the adapter, responsible for joining fun
          8 min read

        • Bridge Design Pattern
          The Bridge design pattern allows you to separate the abstraction from the implementation. It is a structural design pattern. There are 2 parts in Bridge design pattern : AbstractionImplementationThis is a design mechanism that encapsulates an implementation class inside of an interface class. The br
          4 min read

        • Composite Method | Software Design Pattern
          Composite Pattern is a structural design pattern that allows you to compose objects into tree structures to represent part-whole hierarchies. The main idea behind the Composite Pattern is to build a tree structure of objects, where individual objects and composite objects share a common interface. T
          9 min read

        • Decorator Design Pattern
          The Decorator Design Pattern is a structural design pattern that allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class. It involves creating a set of decorator classes that are used to wrap concrete components.Important Top
          9 min read

        • Facade Method Design Pattern
          Facade Method Design Pattern is a part of the Gang of Four design patterns and it is categorized under Structural design patterns. Before we go into the details, visualize a structure. The house is the facade, it is visible to the outside world, but beneath it is a working system of pipes, cables, a
          8 min read

        • Flyweight Design Pattern
          The Flyweight design pattern is a structural pattern that optimizes memory usage by sharing a common state among multiple objects. It aims to reduce the number of objects created and to decrease memory footprint, which is particularly useful when dealing with a large number of similar objects.Flywei
          10 min read

        • Proxy Design Pattern
          The Proxy Design Pattern a structural design pattern is a way to use a placeholder object to control access to another object. Instead of interacting directly with the main object, the client talks to the proxy, which then manages the interaction. This is useful for things like controlling access, d
          9 min read

        3. Behvioural Design Patterns

        geeksforgeeks-footer-logo
        Corporate & Communications Address:
        A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
        Registered Address:
        K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
        GFG App on Play Store GFG App on App Store
        Advertise with us
        • Company
        • About Us
        • Legal
        • Privacy Policy
        • In Media
        • Contact Us
        • Advertise with us
        • GFG Corporate Solution
        • Placement Training Program
        • Languages
        • Python
        • Java
        • C++
        • PHP
        • GoLang
        • SQL
        • R Language
        • Android Tutorial
        • Tutorials Archive
        • DSA
        • Data Structures
        • Algorithms
        • DSA for Beginners
        • Basic DSA Problems
        • DSA Roadmap
        • Top 100 DSA Interview Problems
        • DSA Roadmap by Sandeep Jain
        • All Cheat Sheets
        • Data Science & ML
        • Data Science With Python
        • Data Science For Beginner
        • Machine Learning
        • ML Maths
        • Data Visualisation
        • Pandas
        • NumPy
        • NLP
        • Deep Learning
        • Web Technologies
        • HTML
        • CSS
        • JavaScript
        • TypeScript
        • ReactJS
        • NextJS
        • Bootstrap
        • Web Design
        • Python Tutorial
        • Python Programming Examples
        • Python Projects
        • Python Tkinter
        • Python Web Scraping
        • OpenCV Tutorial
        • Python Interview Question
        • Django
        • Computer Science
        • Operating Systems
        • Computer Network
        • Database Management System
        • Software Engineering
        • Digital Logic Design
        • Engineering Maths
        • Software Development
        • Software Testing
        • DevOps
        • Git
        • Linux
        • AWS
        • Docker
        • Kubernetes
        • Azure
        • GCP
        • DevOps Roadmap
        • System Design
        • High Level Design
        • Low Level Design
        • UML Diagrams
        • Interview Guide
        • Design Patterns
        • OOAD
        • System Design Bootcamp
        • Interview Questions
        • Inteview Preparation
        • Competitive Programming
        • Top DS or Algo for CP
        • Company-Wise Recruitment Process
        • Company-Wise Preparation
        • Aptitude Preparation
        • Puzzles
        • School Subjects
        • Mathematics
        • Physics
        • Chemistry
        • Biology
        • Social Science
        • English Grammar
        • Commerce
        • World GK
        • GeeksforGeeks Videos
        • DSA
        • Python
        • Java
        • C++
        • Web Development
        • Data Science
        • CS Subjects
        @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
        We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
        Lightbox
        Improvement
        Suggest Changes
        Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
        geeksforgeeks-suggest-icon
        Create Improvement
        Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
        geeksforgeeks-improvement-icon
        Suggest Changes
        min 4 words, max Words Limit:1000

        Thank You!

        Your suggestions are valuable to us.

        '); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
        ').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

        You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

        However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
        '); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
        '); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
        '); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
        "For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
        Continue without supporting
        `; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

        What kind of Experience do you want to share?

        Interview Experiences
        Admission Experiences
        Career Journeys
        Work Experiences
        Campus Experiences
        Competitive Exam Experiences