How to use onclick event in JavaScript? - javascript

I'm trying to make a window that slide up when the X button(close.png) is clicked.
I added the Wrap element with JavaScript, and added an img element inside.
Then, I put following JavaScript, but there is no change when I press the X button.
<script>
const parent3 = document.querySelector('#wrap');
const billingField3 = document.querySelector('#woocommerce-input-wrapper');
const newImg = document.createElement('img');
newImg.setAttribute("src", "//t1.daumcdn.net/postcode/resource/images/close.png");
newImg.setAttribute('id', 'btnFoldWrap');
newImg.style.cssText = 'cursor:pointer;position:absolute;right:0px;top:-1px;z-index:1';
newImg.onclick = "offDaumZipAddress();"
parent3.insertBefore(newImg, billingField3);
</script>
function offDaumZipAddress() {
jQuery("#wrap").slideUp();
}
Website structure is
<div class="woocommerce-billing-fields__field-wrapper">
<p class="billing_postcode_find_field">..
<span class="woocommerce-input-wrapper">...
</span>
</p>
<div id="wrap" ..>
<img src="..."></img>
</div>
<p class="billing_address_1_field">
<span class="woocommerce-input-wrapper">
Checking with the console of chrome developer tools doesn't show any errors.
Could someone please let me know what am I missing?
Thank you.

The value of the onclick property must be a function reference, not a JavaScript string.
newImg.onclick = offDaumZipAddress;

You have your answer; here is a working example of that loosely based on your code (so the inserted image actually shows, added some CSS etc. to illustrate)
//gets first one of this type
const billingField3 = document.querySelector('.woocommerce-input-wrapper');
// Get a reference to the parent node/ gets first one of this type
const parent3 = billingField3.parentNode;
//console.log(parent3);
//console.log(billingField3);
// Create the new node to insert
const newImg = document.createElement('img');
newImg.setAttribute("src", "//t1.daumcdn.net/postcode/resource/images/close.png");
newImg.setAttribute('id', 'btnFoldWrap');
newImg.setAttribute('alt', 'folderWrap');
// no not this: newImg.style.cssText = 'cursor:pointer;position:absolute;right:0px;top:-1px;z-index:1';
// this:
newImg.classList.add("inserted-image");
newImg.onclick = offDaumZipAddress;
//console.log("Thing:",newImg);
//console.log("HTML:", parent3.innerHTML);
parent3.insertBefore(newImg, billingField3);
//console.log("New HTML:", parent3.innerHTML);
function offDaumZipAddress() {
console.log('here we go');
jQuery("#wrap").slideUp();
}
.billing_postcode_find_field {
border: solid blue 1px;
padding: 1rem;
}
.woocommerce-input-wrapper {
border: solid 1px lime;
padding: 1rem;
}
.inserted-image {
cursor: pointer;
/* This is odd, makes it not clickable:
position: absolute;
right: 0px;
top: -1px;
z-index: 1;*/
border: solid 1px red;
min-width: 1.5rem;
min-height: 1.5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="woocommerce-billing-fields__field-wrapper">
<p class="billing_postcode_find_field">..
<span class="woocommerce-input-wrapper">...</span>
</p>
<div id="wrap">
<img src="//t1.daumcdn.net/postcode/resource/images/close.png" alt="png"></img>
</div>
<p class="billing_address_1_field">
<span class="woocommerce-input-wrapper"></span>
</div>

Related

Select Image with Javascript and save ID

I have a div container with several images. I want the user to select an image (avatar) from the provided list. Then the avatar image will be uploaded and also accessible. Once the user selects the avatar, I want to save the location of the selected avatar to my database. What is the best way to select the image? Is there any easy way to do this?
HTML
<div class="image-container">
<img src="images/gorillaAvatars/brownGorilla.png" id="brownGorilla">
<img src="images/gorillaAvatars/gorilla.png" id="Gorilla">
<img src="images/gorillaAvatars/greenGorilla.png" id="greenGorilla">
<img src="images/gorillaAvatars/kidGorilla.png" id="kidGorilla">
<img src="images/gorillaAvatars/surpriseGorilla.png" id="surpriseGorilla">
</div>
CSS
<style>
.image-container{
width:60%;
border: solid magenta 1px;
padding: 5px;
margin: 30px;
display: flex;
justify-content: space-evenly;
}
img{
width:80px;
}
img:hover,
img:focus,
img:active{
background-color: blue;
border-radius: 20px;
}
<style>
Javascript
const brownGorillaAvatar = "https://brownGorilla.png";
const mainGorillaAvatar ="https://gorilla.png"
const greenGorillaAvatar ="https://greenGorilla.png"
const kidGorillaAvatar ="https://kidGorilla.png"
const surpriseGorillaAvatar ="https://surpriseGorilla.png"
const avatar = [brownGorillaAvatar,mainGorillaAvatar,greenGorillaAvatar,kidGorillaAvatar, surpriseGorillaAvatar]
brownG.addEventListener('click', avatarSelect);
bigG.addEventListener('click', avatarSelect1);
greenG.addEventListener('click', avatarSelect2);
kidG.addEventListener('click', avatarSelect3);
surpG.addEventListener('click', avatarSelect4);
function avatarSelect (){
console.log(avatar[0])
}
function avatarSelect1 (){
console.log(avatar[1])
}
function avatarSelect2 (){
console.log(avatar[2])
}
function avatarSelect3 (){
console.log(avatar[3])
}
function avatarSelect4 (){
console.log(avatar[4])
}
Rather than attaching an event to each image object, it would be better to attach an event to the container surrounding it.
You can avoid overlapping codes and respond flexibly even if image objects increase.
for example
const imageContainer = document.getElementById("image-container");
imageContainer.onclick = function(e) {
console.log(e.target.id); // you can get img tag's id
}
Have a look at how Event Bubbling and delegation work in javascript to get a better understanding but you want to add the event to the parent container not to each element. So by adding new elements to your array they will be clickable.
const avatars = [
'brownGorillaAvatar',
'mainGorillaAvatar',
'greenGorillaAvatar',
'kidGorillaAvatar',
'surpriseGorillaAvatar'
]
const avatarContainer = document.querySelector('#avatarContainer');
avatars.forEach((avatar) => {
const span = document.createElement('span');
span.innerHTML = avatar;
avatarContainer.appendChild(span);
})
avatarContainer.addEventListener('click', (evt) => {
console.log(evt.target);
})
<html>
<head></head>
<body>
<section id="avatarContainer">
</section>
</body>
</html>

How to use javascript to add classes to text and image

I would really appreciate help with running a query for .parentContainer, then find text ABC123 and wrap this in a div with ID="abc123". I already have some simple code that will add content to the new div element.
Further to that, is it possible to also query .parentContainer for the presence of ABC123, and then add a new class to the image if ABC123 exists?
Sorry if I appear a bit lazy here. I have really only started dabbling with JavaScript and have been reading lots on manipulation of the DOM. I tend to learn loads from studying and tweaking code that can apply to my own real scenarios.
Thanks so much!
let parentContainers = document.querySelectorAll('.parentContainer')
for(let [i,f] of parentContainers.entries()){
if(f.innerText.includes('ABC123')){
let div = document.createElement('div');
div.innerText = 'ABC123';
div.setAttribute("id", "abc123");
f.append(div)
}
}
#ABC123 {
border: 3px solid red;
}
#abc123 {
border: 3px solid green;
}
.abc123 {
border: 2px solid purple;
}
.parentContainer {
padding: 10px;
border: 2px solid black;
margin: 10px 0;
}
<div class="parentContainer">
<a class="productImage" href="https://www.mywebsite.com/product-1"><img src="https://via.placeholder.com/350x150" alt="Product 1 Image"></a>
<div class="productInfo">
ABC123
Product summary description goes here.
</div>
</div>
<div class="parentContainer">
<a class="productImage" href="https://www.mywebsite.com/product-1"><img src="https://via.placeholder.com/350x150" alt="Product 1 Image"></a>
<div class="productInfo">
ABC123
Product summary description goes here.
</div>
</div>
Try this out
let parentContainers = document.querySelectorAll('.parentContainer')
for(let [i,f] of parentContainers.entries()){
if(f.innerText.includes('ABC123')){
let div = document.createElement('div');
div.innerText = 'ABC123';
div.setAttribute("id", "abc123");
f.append(div)
}
}

How to make sure a click event has an effect only on the intended class?

Here is the important part of the code that executes.
Im trying to click on one element with a particular ID that relates to bookmarking the message but the element keeps triggering another click event that hides every div with the class 'messageCase' while at the same time attaching class messageOpen2 to the bookmark images ID which is very odd
the 'hidden' classes just hide all other message instances that contain
The messageCase class.
var openMessageAnimationStrategy = function () {
var openMessage = $(document).ready(function () {
var divTarget = $("div.messageCase");
$(divTarget).click(function (e) {
var target = $(e.target);
target.toggleClass('messageOpen2');
divTarget.addClass('hidden');
target.removeClass('hidden');
});
});
};
Here is what the HTML looks like
<div class="messageCase">
<div class="messageImageBox">
<div id="messageImage">
</div>
</div>
<div id="subjectLine">
Subject Line Text
</div>
<div id="bookMarkImage">
<img id="bookmarkStatus" class="savedMessage" src="notbookMarked64.png" />
</div>
<div class="activeBookmarks">
{38} <br />
Bookmarks <br />
<br />
9:53am
</div>
<div id="bodyPreview">
Body Preview Text is light
</div>
</div>
Every Time I use the Click event on bookmarkStatus to change the src of the image it causes the first click event to execute making everything disappear & the class messageOpen2 to be added to bookmarkStatus. I can include the CSS if necessary but ill list the code for the bookmarking function below
var bookmarkedStrategy = function () {
var bookmarkedStrategy = $(document).ready(function () {
var bookmarkStatus = $("#bookmarkStatus");
var divTarget = $('messageCase');
//below trying to remove the Class that was attached by the initial function while also changing the image SRC for the class bookmark
$(divTarget).click(function (e) {
var target = $(e.target);
divTarget.removeClass('messageCase2');
bookmarkStatus.toggleClass('savedMessage');
});
});
};
I Think the main problem has to do with the initial function but I don't know what else could be wrong any ideas?
edit Here is the CSS that matters.
.savedMessage {
background-image: url("bookmarked64.png");
}
.messageOpen2 {
height: 250px;
}
.messageCase {
margin: 5px;
border-radius: 5px;
background-color: aliceblue;
height: 70px;
}
#bookMarkImage {
float:right;
height:64px;
width:64px;
z-index:9999;
}
.hidden {
display:none;
max-height: inherit;
}
.activeBookmarks {
float: right;
text-align: center;
font-size: 13px;
font-weight: 700;
text-decoration: solid;
}
Calling code
var bookmarkedthings = new MessageHandling(bookmarkedStrategy);
bookmarkedthings.greet();
var openMessage = new MessageHandling(openMessageAnimationStrategy);
openMessage.greet();
There is a missing . in your bookmarkedStrategy function code var divTarget = $('.messageCase'); Add dot and try again

Javascript not working on some element by id's

I'm attempting to make 3 lines do something:
line 1 rotate 45deg and some translate
line 1 opacity 0
line 1 rotate -45deg and some translate
JS Fiddle
<a href = "#"><div id = "menu" onclick="menu()">
<div id = "lineOne">1</div>
<div id = "lineTwo">1</div>
<div id = "lineThree">1</div>
</div>
</a>
function menu()
{
//Show Differnet Button
document.getElementById('lineOne').style.WebkitTransform = "rotate(45deg) translate3d(10px,10px,0)";
document.getElementById('lineTwo').style.opacity = ".3";
document.getElementById('lineThree').style.WebkitTransform = "rotate(-45deg) translate3d(10,-10px,0)";
}
#lineOne, #lineTwo, #lineThree, #line4, #line5, #line6
{
margin-top: 6px;
margin-left: 30px;
position: relative;
top: 0px;
right: 0px;
width: 50%;
height: 7px !important;
background: black;
color: rgba(1,1,1,0) !important;
}
My code on JS Fiddle is above, and the only result I am getting is the opacity and the first one rotates and translates. Nothing else. I completely ignores the rest. What can I do?
You are missing a px in your transform.
document.getElementById('lineThree')
.style.WebkitTransform = "rotate(-90deg) translate3d(10px,-10px,0)";
translate3d requires length units.
There were lots of problems. Here's a working fiddle: http://jsfiddle.net/FK499/42/
First you needed to tell it to put the js in the <head> by setting it to "No wrap - in <head>"
Second, your function wasn't closed with a }.
Third, you didn't need the anchor tag.
Fourth, you were missing the px in the last transform.
HTML:
<div id = "menu" onclick="menu();">
<div id = "lineOne">1</div>
<div id = "lineTwo">1</div>
<div id = "lineThree">1</div>
</div>
and the js:
function menu()
{
//Show Differnet Button
document.getElementById('lineOne').style.WebkitTransform = "rotate(45deg) translate3d(10px,10px,0)";
document.getElementById('lineTwo').style.opacity = ".3";
document.getElementById('lineThree').style.WebkitTransform = "rotate(-45deg) translate3d(10px,-10px,0)";
}

Edit link on div mouseover

On facebook for example - when you put your mouseover a news item, a remove button appears. How can I go about making this happen?
Thanks,
Elliot
Modern Browsers
In modern browsers, you can leverage the :hover pseudo class in our selector. As an example, consider the following markup:
<div class="item">
<p>This is a long string of text</p>
<div class="adminControls">
Delete Item
</div>
</div>
By default, we would want the .adminControls to be hidden. They should, however, become visible once the user has hovered the .item element:
.item .adminControls {
display: none;
}
.item:hover .adminControls {
display: block;
}
JavaScript and jQuery
If you're using jQuery, you can accomplish this rather easily using the $.hover() method. If you're using Prototype, you can get the protoHover plugin to achieve the same result, or view this blog post.
$("div.item").hover(
function () { $(this).find(".adminControls").show(); },
function () { $(this).find(".adminControls").hide(); }
);
That would accomplish the show/hide effect for the following:
<div class="item">
<p>This is a long string of text</p>
<div class="adminControls">
Delete Item
</div>
</div>
<div class="item">
<p>This is a long string of text</p>
<div class="adminControls">
Delete Item
</div>
</div>
<div class="item">
<p>This is a long string of text</p>
<div class="adminControls">
Delete Item
</div>
</div>
If you don't need to support IE6, you can use the :hover pseudoclass like so:
CSS:
.link { display: none; }
.item:hover > .link { display: inline; }
HTML:
<div class="item">
Remove
Lorem Ipsum...
</div>
Position the link as you'd like it to appear on hover, then hide it with JavaScript and use the onmouseover event to show it. (i.e., it's display: none; and then turns to display: block; when the onmouseover event is triggered).
Something like this:
window.onload = function(){
document.getElementById('mylink').style.display = 'none';
document.getElementById('mydiv').onmouseover = function(){
document.getElementById('mylink').style.display = 'block';
}
}
You need to write a Javascript function that manipulates the DOM and you need to associate the OnMouseOver attribute of your HTML element with that function. For example, on my home page a picture of my face changes every time the mouse rolls over it. The Javascript function is defined in the HTML page itself.
<script type="text/javascript">
<!--
faceCnt = 7;
var faces = new Array( faceCnt );
var faceDates = new Array( "1982", "1986", "1991", "1999", "2004", "2006", "2009" );
var faceIdx = 7; /* So that first change is to earliest one. */
for( var idx = 0 ; idx < faceCnt ; idx++ )
(faces[idx] = new Image(150, 116)).src = "david/david" + (idx + 1) + ".jpg";
function nextFace( ref )
{
faceIdx = faceIdx >= faceCnt - 1 ? 0 : faceIdx + 1;
ref.src = faces[ faceIdx ].src;
ref.title = "David-" + faceDates[ faceIdx ];
}
//-->
</script>
<img id="myface" src="david/david7.jpg" alt="david" title="David-2009"
width="150" height="116"
style="margin: 0 0 5px 15px; /* -10px -5px 10px 10px; */
padding: 0;
border: solid black;
border-width: 1px;
float: right;"
onMouseOver="nextFace( this )"
onClick="nextFace( this )" >

Categories

Resources