Certain code will not execute if a JavaScript div is inside a container div

Having trouble with executing specific commands on a div inside a container? I've got a function called doFunc() that doesn't seem to work when assigned to the div with id "x1" inside the container. Strangely enough, if I move the div outside of the container, everything runs smoothly. My goal is to create a button in the top right corner of an image for shrinking it (I styled it using CSS). Clicking the image should enlarge it using my large() function, and clicking the X should shrink the picture and hide the X div. The alert("I tried!") command works fine when the X div is within the container, but the resize command only works if the X div is moved outside its container (which is not where I want it to be). Any HTML and JavaScript gurus out there who can guide me on how to make these two lines of code execute without compromising my "Click the X to close" concept?


document.getElementById(containerId).style.width="300px";
document.getElementById(xId).style.display="none";

HTML-

<div class="container" id="container1" onclick="large('container1','x1')">
<img src="icecream.jpg">
<div class="x" id="x1" onclick="doFunc('container1','x1')">X</div>
    </div>

JavaScript-

function large(containerId, xId){
document.getElementById(containerId).style.width="600px";
document.getElementById(xId).style.display="block";
}
function doFunc(containerId, xId){
document.getElementById(containerId).style.width="300px";
document.getElementById(xId).style.display="none";
alert("I tried!");

Answer №1

Take a moment to review the functional code provided below.

The problem arises when you click on the div with the identifier x1. This action triggers the onclick event of its parent div, container1, resulting in an increase in width. As a result, clicking on x1 first calls the doFunc function which reduces the width. Subsequently, due to event bubbling, the parent container receives the onclick event and invokes the large function, causing the width to increase again.

Therefore, it appears as though nothing has changed.

This issue is addressed by preventing event bubbling using e.stopPropagation().

function large(containerId, xId){
document.getElementById(containerId).style.width="600px";
document.getElementById(xId).style.display="inline";
}
function doFunc(e, containerId, xId){
  e.stopPropagation();
  e.preventDefault();
document.getElementById(containerId).style.width="300px";
document.getElementById(xId).style.display="none";
//alert("I tried!");
  }
.container
{
  width: 300px; 
 }

.x {
 display: none; 
 cursor: pointer;
}
<div class="container" id="container1" onclick="large('container1','x1')">
<img width="100%" src="http://pisces.bbystatic.com//BestBuy_US/store/ee/2015/com/pm/nav_desktops_1115.jpg">
<div class="x" id="x1" onclick="doFunc(event, 'container1','x1')" style="float:right">X</div>
    </div>

Answer №2

the reason this happens is because if you place the function inside the container div, it will also run when you click on the second function. To solve this, move the function to a different div, like I did in my example where I placed it on the image itself. (just replace the image)

function changeSize(containerId, imageId){
document.getElementById(containerId).style.width="600px";
document.getElementById(imageId).style.display="block";
}
function revertSize(containerId, imageId){
document.getElementById(containerId).style.width="300px";
document.getElementById(imageId).style.display="none";
}
<div class="container">
<img id="newImg" onclick="changeSize('newImg','close')" style="max-width:100%;max-height:100%;" src="https://example.com/image.jpg">
<div class="close" id="close" onclick="revertSize('newImg','close')">X</div>
</div>

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

Transferring contacts from Gmail, Yahoo, Hotmail, Facebook, and Twitter

Looking to streamline the process of importing contacts from various platforms like gmail, yahoo, hotmail, and facebook using Google API's. Are there any libraries available that can handle this task or should I dive into writing code for all the diff ...

Using Node.js to showcase MySQL data in an HTML table

Currently, I am in the process of learning how to utilize node.js with mysql. Despite my efforts to search for comprehensive documentation, I have not been successful. I have managed to display my mysql data on my browser, but ultimately I aim to manage it ...

Issue with Wordpress Submenu Items not Displaying

I've included sub menu items in my primary navigation, but they're not visible at all? I've examined the css and haven't found any code that would hide the sub menu. ul.art-hmenu { display: inline-block; vertical-align: midd ...

Provider $uibModalProvider is not recognized as it is linked to $uibModal which in turn is associated with the modalPopDirective

I am currently using Angular's $uibModal in an attempt to create a popup when the page loads, but unfortunately it is not functioning as expected. I suspect there may be an issue with the directive. Here is the code snippet in question: angular.modul ...

Changing a JavaScript array by including a numerical value

Here is my original dataset... [{ month: 'Jan', cat: 'A', val: 20 },{ month: 'Jan', cat: 'B',' val: 5 },{ month: 'Jan', cat: &ap ...

What is causing the content to overflow outside of the navbar on smaller screens or mobile devices?

/* *{ font-family: sans-serif; box-sizing: border-box; margin: 0; padding: 0; overflow-x: hidden; } */ .main { min-height: calc(100vh - 10rem); display: grid; place-items: center; } p { font-size: 4rem; line-height: 1.6; } nav ...

Concealing errors during field updates in Angular form validation

Currently, my form consists of just one field with a few validation rules: <form name="my_form" novalidate ng-controller="FormController"> <label>Your Name:</label> <input type="text" ...

Sending data from a template to a JavaScript file via context variable

This discussion thread here explored the use of variables in inline JavaScript within templates. Suppose I have individual .js files with scripts located in the static folder, like so: utils.js const createButton = (buttonCount) => { containerId = ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

How can I use Express JS and Mongoose to update an array of objects in MongoDB?

Encountered a TypeError: result.taskList[id].push is not a function const taskcancel = (user, pswd, id) => { return db.Todotasks.findOne({ username: user, password: pswd }).then((result) => { if (result) { console.log(result.tas ...

Disregard the Margin of Ancestor Elements

I'm attempting to make an image span the full width of a parent element, but the parent element has a margin of 10px. This means that when I apply #parent img { position: absolute; top:0; left:0; height: auto; width: 100% } It on ...

Javascript and iframes may encounter compatibility issues with browsers other than Internet Explorer

My HTML file includes an iframe and JavaScript that function correctly in IE Browser, but they do not work in other browsers such as Safari and Firefox. When using Safari, only the iframe box is displayed without showing the content inside it. I am curio ...

Tips for creating a custom axios response depending on the error code returned by the response

I am currently working on implementing a global error handling system in my Vue application. Within my project, I have an api.service.js file that contains the necessary code for Axios setup and various HTTP request functions such as get and post: /** * S ...

Display solely the content within a specific Div

Currently facing an issue that needs to be resolved. I have a number of divs, each of which reveals a Span containing some text when hovered over. I've written a jQuery script for this functionality, but it currently displays all the Span elements whe ...

Using the spread operator to pass properties in React

Update: After delving deep into the documentation, @wawka has discovered that there may be some issues with the react-router-dom v^5.0.1 causing problems with the myLink2 component. It seems like a rewrite of this component may be necessary. In my React p ...

Steps for setting up Node.js or npm on XAMPP

Hello there, I'm new to all of this so please bear with me if I make any mistakes. As a beginner developer, I am currently working on developing a web application locally using XAMPP. My plan is to eventually deploy it using a hosted web service. XAM ...

What is causing the #wrapper element to not fully contain all of its content within?

I am struggling to figure out why the wrapper on this page is not properly wrapping the content. It's only 332px tall for some reason when it should be the height of the content, which is causing the footer to pull up to the top of the page. Could I b ...

Passing props from a parent component to a nested child component in Vue 3

My goal is to achieve the functionality described in the title. Suppose I have the following structure: parent -> child -> secondChild Currently, there is a variable called isActive in the parent component. Below is how it can be implemented: paren ...

Steps to show the chosen index value in an alert pop-up using Ionic 2 framework

I'm in the process of trying to showcase a selected index value within an Ionic 2 alert box. However, I'm struggling to find the correct method to display it in the Ionic prompt. This pertains to the home.ts import { Component } from '@ang ...

Tips for positioning the cursor at the beginning of text and shifting the focus to the start while utilizing the MaterialUI Input component

I have scoured various online forums for a solution to this issue, but none of the suggestions seem to work. Although I managed to position the cursor at the beginning of the text, it did not shift the focus accordingly. Here is the code snippet for the co ...