Ways to showcase .toggle or .Animate to every linked browser session with the help of Meteor

Have you ever wondered how to demonstrate the interaction of clicking on an element that triggers a toggle or animation? Check out this meteor checkers example:

In the scenario below, I envision every browser connected to the Meteor server to witness shape changes made by other browsers.

View the example here: https://jsfiddle.net/qh2jyL3b/

HTML:

<div class="square"></div>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>

CSS:

.square {
  width: 100px;
  height: 100px;
  background: white;
  border: 10px solid black;
  cursor: pointer;

}

JavaScript:

$(".square").click(function() {
    $( this ).toggleClass("circle");
  });

Answer №1

If you want to save the click state in a Meteor.Collection, you can achieve this easily. Any changes made to the collection will be updated reactively for all connected clients. All you need to do is create a separate document for each square and store the state there. Then, you can set up a helper function that displays the correct class name based on the database items.

Here's an example of how you can do it:

You can create a separate document for each chess table on the server side like this:

ChessTableCell = new Mongo.Collection('chesstablecell');

You can then store the state of each cell in these documents. Initially, you can insert the following:

ChessTableCell.insert({name: 'a1', state: false});
ChessTableCell.insert({name: 'a2', state: false);

...and so on

On the client side, you can access the cell states like this:

ChessTableCell.findOne({name: 'a1'}).state;

When a cell is clicked, you simply need to toggle the state of that cell. You can do this by:

Template.chessboard.events({
    'click .cell': function(e,t) {
      var cellName = $(e.target).data('name'); //assuming you have specified cell name in your HTML data-name attribute
      var cellValue = ChessTableCell.findOne({name: cellName}).state;
      //update the value here
      ChessTableCell.update({name: cellValue}, {$set: { state: !cellValue}});
    }
});

This way, the state will change reactively on every connected client. Remember to reflect these updates in your HTML as well, like so:

{{#each ChessTableCells}}
  <div class="cell {{#if state}}active{{/if}}" data-name="{{name}}"></div>
{{/each}}

In your client code, you can set up helpers like this:

Template.chessboard.helpers({
  ChessTableCells: function() { return ChessTableCell.find({}); }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding the active class in Bootstrap can be easily achieved in CodeIgniter by using the

I am seeking guidance on how to add an active class in CodeIgniter when dividing the view into three separate files. These files include: header.php page1.php ... page10.php footer.php According to this thread, there seems to be no clear solution prov ...

Optimizing jQuery UI autocomplete choices through filtering

Currently utilizing the jqueryUI autocomplete feature on my website. Let's say I have the following entries in my database... apple ape abraham aardvark Upon typing "a" in the autocomplete widget, a list appears below the input field displaying the ...

Executing a method in an applet using JavaScript

I am trying to print some information using an applet. The applet is located in the signed qds-client.jar file and has the following code: public class PrintText extends Applet implements Printable { private ClientAccount clientAccount; public Client ...

Using Javascript to redirect to a link using JSON

Is there a way to display the CustomerPartial without reloading the page or triggering a postback when a button is clicked? Currently, when I click the button, data is posted to Home/Customer but the browser link always remains as: localhost:49461 How ca ...

Unauthenticated user attempting to send a post request via React JS without proper authentication

Currently, I am working on a project where I am following a video tutorial that demonstrates how to authenticate a user using node and passport JS. The tutorial itself uses Hogan JS as its view engine, but I have decided to implement React as my front end ...

Setting up GameClosure on a Windows machine

Is it possible to install GameClosure on Windows? The installation guide mentions that only OSX is officially supported, but there have been reports of success running it on Linux and Windows. However, the process for doing this is not well-documented. A ...

A guide on how to retrieve POST form fields in Express

My form design is quite simple: <form id="loginformA" action="userlogin" method="post"> <div> <label for="email">Email: </label> <input type="text" id="email" name="email"></input> </div> & ...

Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin. My goal is to apply the range slider to filter out data in the last column. In my attempt, I am using search.push to accomplish this filtering process. Below is an example of my i ...

Unique vertical accordion menu design for WordPress websites

I'm currently working on a WordPress website and I'm trying to create a custom menu. My goal is to make the parent element act as an "accordion header" if it has a child "ul". The current setup works fine for up to 2 levels, but if there are more ...

Having trouble retrieving the value from json_encode

<!-- DATABASE QUERY --> $insertstatement = 'SELECT count(*) co FROM `tbl_user` WHERE username="'.$username.'" AND password="'.$password.'"'; ...

Tips for iterating through a nested JSON response using Vue.js

Recently, I started exploring Vue JS and encountered a challenge while looping through API responses using v-for. Below is the snippet from my code: Get Coins Data <div v-for="coin in coinsData">{{coinsData.data.coins.name}}</div> T ...

Utilizing Selenium and Python to Extract Links from a Web Table

Currently, I am faced with a table that has two columns and an unknown number of rows. My task involves utilizing Selenium (with Python) to extract all the links from the second column and compile them into a list. https://i.sstatic.net/bvYez.png The obj ...

Switch the image source when hovering over a text menu

Currently, I have been using the following code to switch between images. However, what I actually want to do is change the image when hovering over the title link of the image. onmouseover="this.src='Images/img.png'" onmouseout="this.src=' ...

Creating a custom autocomplete search using Angular's pipes and input

Trying to implement an autocomplete input feature for any field value, I decided to create a custom pipe for this purpose. One challenge I'm facing is how to connect the component displaying my JSON data with the component housing the autocomplete in ...

Invoke the controller function to retrieve information on the client side

I need to make a call to a server-side controller method that will return a string, eventually formatted as JSON. Once I receive this data on the client side, I want to use it to update a specific part of the user interface. Here is my current setup: Con ...

Leverage the powers of velocity, meteor, and Travis CI to enhance your

After developing a simple Meteor application, I incorporated velocity along with mocha. To integrate my project with Travis CI, I followed the guidelines provided in the suggested .travis.yml file: language: node_js node_js: - "0.10" before_install: - ...

The process of transforming four columns into two columns and two rows

I am aiming to create a layout that displays 4 columns on desktop and then breaks down into 2 columns and 2 rows on smaller screens. https://i.stack.imgur.com/GZ4nQ.png https://i.stack.imgur.com/5ZCrQ.png Any suggestions on how I can achieve this layout ...

Issue encountered while attempting to write KML objects to Google Earth API: NPObject error

Currently, I am working on a script that aims to extract data from Facebook and display it graphically on a Google Map using simple extruded polygons. The social integration and AJAX functionality are both working fine for me. However, whenever I try to ex ...

Preventing XSS Attacks through the Use of Ajax Get and Post Requests

I don't have much knowledge about how to prevent XSS vulnerabilities, especially when it comes to form inputs like not allowing special characters such as <,>. However, I do have a question regarding Ajax: For GET Requests: How can we effici ...

How to retrieve a Typescript variable within an ngIf conditional statement in Angular

How can I access a TypeScript variable inside an ngIf statement? TS: public data: string; HTML: <td> <div *ngIf="data === 'BALL' ; else noplay" >{{ play }}</div> <ng-template #noplay> {{ gotohome ...