How Do You Make Clickable Divs?

Hey guys,

Short question here: how do you make clickable divs?

I have tried adding click events to them and it’s not working for me. I’ve tried making very large anchor tags full of content, and that doesn’t work either.

Thanks for the help.

(post deleted by author)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="clickable">Here is my clickable div</div>
    

    <script src="index.js"></script>
</body>
</html>

index.js

document.getElementById('clickable').addEventListener('click', clickDiv);

function clickDiv() {
    document.getElementById('clickable').innerHTML = "Clicked and Changed"; // Changes text inside div one time only when clicked
}

For example.
Just click on the text to make the text change.

Yeah, I need to use JavaScript to do something with the text when it clicks and it’s not working. Perhaps it’s because I’m using jQuery. Here’s an example of some html:

<a class="content subject">
   <div>
      <img class="labelImg" src="icons/bookIcon.png">
      <div class="colon">:</div>
   </div>
   <label class="contentLabel">Math</label>											
</a>

And here’s the jQuery I’m using to add click event:

$('.content.subject').click(function()
						{
							console.log("Clicked");
                        });

I see nothing in the console when I click the anchor tag.

Your code works.
Probably you haven’t included jQuery.

It’s very odd. I know that jQuery was added correctly because I have other buttons on the page that use it and work just fine. However, these particular anchor tags do nothing when I click them.

(post deleted by author)

In case anyone is still interested, as I was trying to debug my program I realized that even on the buttons where the click event works, it only work once for some reason.

Anyone have any idea as to why that is?

Though I’ve never had this problem before (as usually the click events just work) I figure it has something to do with the DOM loading or something.

Your help is greatly appreciated!

Post your code on codepen.io or jsfiddle.net so we can see it.

Alright, as of writing this, I’m not sure how to put the code on this forum from codepen or jsfiddle, so I’ll just put it here for now (I’ll learn how to do that later for future use though :slight_smile: )

So, I’m using ajax to put some data into a database and then immediately display it back to the user:
pic1
pic2
pic3


I also want to be able to click the div, save some of the text information somehow, and then go to some other page, somehow having saved the text information in the next JavaScript file. Right now, I’m trying to figure out how to make the divs clickable in the first place…

Here’s the full html:

<html>
	<head>
		<link href = "css/mobileStyle.css" media = "screen and (max-device-width: 592px)" rel = "stylesheet" type = "text/css"/>
		<script src = "https://code.jquery.com/jquery-3.3.1.min.js"></script>
	</head>

	<body>
		<div id = "container">
			<div id = "header">
				<div id = "title">
					<h1>SUBJECT</h1>
				</div>
				<div id = "path">
				</div>
			</div>
			<form id = "subjects" class = "contentContainer">
				<input type = "button" class = "addButton" value = "+"/>
			</form>
		</div>
		<script src = "js/subject.js"></script>
	</body>
</html>

Here’s the JavaScript:

var subjects;
var dt;

function addSubjectFunctionality() {
    /*
    for debugging purposes
    */
    dt = new Date();
    getSubjects();
    var newDivExists = false;
    var newSubject;
    $('.addButton').click(function() {
        console.log("newDivExists = " + newDivExists);
        if (!newDivExists) {
            newDivExists = true;
            $('#subjects').prepend("<div id = \"newSubject\" class = \"content\">\
															<div>\
																<img class = \"labelImg\" src = \"icons/bookIcon.png\"/><div class=\"colon\">:</div>\
															</div>\
															<input class = \"customizeInput\" type = \"text\" placeholder = \"Subject Name\"></input>\
															<a class = \"cancelButton\">Cancel</a>\
														</div><br/>");
        }

        $(".customizeInput").keypress(function(e) {
            if (e.which == 13) {
                e.preventDefault();
                newSubject = $(this).val();
                console.log("newSubject = " + newSubject + "numInputs = " + $(".customizeInput").length);
                $.ajax({
                    method: 'POST',
                    url: 'phpScripts/subjectStoreItems.php',
                    data: {
                        subject: newSubject
                    },
                    success: function(data) {
                        console.log(data);
                        $('#subjects').html("<input type = \"button\" class = \"addButton\" value = \"+\"/>");
                        newDivExists = false;
                        console.log("newDivExists = " + newDivExists);
                        getSubjects();
                    }
                });
            }
        });

        $(".cancelButton").click(function() {
            $(this).parent().remove();
            newDivExists = false;
        });
    });

    $('.content.subject').click(function() {
        console.log("Clicked");
    });
}

function getSubjects() {
    console.log("getting subjects " + dt.getTime());
    $.ajax({
        method: 'POST',
        url: 'phpScripts/subjectGetItems.php',
        success: function(data) {
            var innerHtml = "";
            subjects = JSON.parse(data);
            console.log("From within getSubjects(): subjects.length = " + subjects.length + "; subjects[0].subject = " + subjects[0].subject + " " + dt.getTime());
            for (var i = 0; i < subjects.length; i++) {
                innerHtml += "<a class = \"content subject\">\
												<div>\
													<img class = \"labelImg\" src = \"icons/bookIcon.png\"/><div class = \"colon\">:</div>\
												</div>\
												<label class = \"contentLabel\">" + subjects[i].subject + "</label>\
											</a><br/>";
            }
            $('#subjects').prepend(innerHtml);
        }
    });
}

function getIdFromSubject(target) {
    for (var i = 0; i < subjects.length; i++) {
        if (subjects[i].subject === target) {
            return subjects[i].id;
        }
    }
}
addSubjectFunctionality();

Now, you’ll notice that the ajax functions are making calls to php files. That gets quite complicated (and I’ll put all the code on my github, https://github.com/AliouneY, to make all this a little bit clearer [also, if you wanted to help me develop that would also be cool, I need the git practice!]). For now I’ll just show you the code for some php classes and let you figure out what’s going on:

db.php:

<?php

	class DB
	{
		private $host = "127.0.0.1";
		private $db_name = "oop_flashcardpwa";
		private $db_uname = "root";
		private $db_pass = "";
		private $db_socket_type = "mysql";
		
		private $instance = NULL;
		
		public function __construct()
		{
			if($this->instance == NULL)
			{
				try
				{
					$dbInstance = new PDO("".$this->db_socket_type.":dbname=".$this->db_name.";host=".$this->host, $this->db_uname, $this->db_pass);
					$this->instance = $dbInstance;
				}
				catch(PDOException $e)
				{
					echo "Connection failed: " . $e->getMessage();
				}
			}
		}
		
		public function runQuery($query) //I would've named this query, but I realized that another query function exists
		{
			$sqlQuery = $this->instance->prepare($query);
			$sqlQuery->execute();
			return $sqlQuery;
		}
		
	}

app.php:

<?php

	include 'db.php';

	interface appFunctionality
	{
		public static function getItems();
		public static function storeItem();
	}
	
	class subjectSystem implements appFunctionality
	{
		public static function getItems()
		{
			$subjects = Array();
			$db = new DB();
			$query0 = $db->runQuery("SELECT * FROM subjects");
			
			while($rows = $query0->fetch(PDO::FETCH_ASSOC))
			{
				$subjects[] = $rows;
				/*$innerHtml = $innerHtml . "<a class = \"content\">
												<div>
													<img class = \"labelImg\" src = \"icons/bookIcon.png\"/><div class = \"colon\">:</div>
												</div>
												<label class = \"contentLabel subject\">". $subjects['subject'] ."</label>
											</a><br/>";*/
			}
			echo json_encode($subjects);
			unset($db);
		}
		
		public static function storeItem()
		{
			$db = new DB();
			
			if(isset($_POST['subject']))
			{
				$subject = $_POST['subject'];
				$query0 = $db->runQuery("INSERT INTO subjects (subject) VALUES ('$subject')");
				if($query0 !== false)
				{
					echo "Successfully entered " . $subject . " into the database";
				}
			}
			unset($db);
		}
		
	}
	
	class topicSystem implements appFunctionality
	{
		public static function getItems()
		{
		}
		
		public static function storeItem()
		{
		}
	}
	
	class flashcardSystem
	{
	}

subjectGetItems.php:

<?php
	include '../classes/app.php';
	
	subjectSystem::getItems();

Now, this application I’m building is full of problems!

  1. I can’t click the “divs” that display the information from the database

  2. I notice that if I keep clicking the add button while newDivExists = true, it will actually add the data into the database the number of times that I clicked the button (I originally assumed that this was because it must have been creating inputs, which is why I have that whole console.log("Inputs = " + $(.customizeInputs).length) line; you’ll find that this value is always 1; I have no idea what’s going on)

  3. And of course, the add button only works before you press the enter button. After that it stops working!

I’m sure all the errors are front end, I just can’t figure out what they are.

Again, I really appreciate your help.

You can simply post a codepen link and then we can view the code on that site. However, since you code includes PHP, that is not possible. Since you have frontend and backend files, you should publish your code to GitHub and then people can download your entire code to test on their local machines.

Yeah, I’m about to do that now.

Alright, the code is on my github account. Here’s the link: https://github.com/AliouneY/OOP_FlashCardPWA

I realized I didn’t represent the database on github. Well, now it’s there. You can use the db.sql file to (at least guide you on how to) make the database. Sorry for the inconvenience (if any of you are still there :laughing:)

I just quickly looked at your code, but what’s happening here?:

$('#subjects').html("<input type = \"button\" class = \"addButton\" value = \"+\"/>");

That’s the equivalent of saying
document.getElementById("subjects").innerHtml = "<input etc. />";

Now that I think of it, the problem may be that I’m creating a new button without adding any new event listener. I’m trying to fix that now

And doesn’t the same happen with the newly created divs?

How? I could understand if this occurred after I press the enter button because of the line of code after that which says to delete everything and then get the newly created divs again, but what about when I freshly load the page? The event listeners should be there, but the divs are never clickable (that is, I never get the console message after I click them).

Oh hey, I just solved all my problems! Thank you all so much for your support!

You make the div’s click event in jQuery:

$("div").click(function(){
  alert("The div was clicked.");
});