JQuery "click" not triggering function - javascript

I'm trying to trigger a JQuery function when you click on a div (i've tried making it a button as well) to no avail. Google Chrome Inspector does not even recognize an event handler being created behind the scenes.
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">;
<script type = "text/javascript" src = "http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id = "main" style = "width: 500px; height: 500px; background-color: black; color: white;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius aliquam nobis optio ut ratione a eligendi excepturi cumque est commodi? Sed, odit, culpa deserunt distinctio at commodi modi architecto aliquam.
</div>
<button class = "button" href="#" style = "width: 50px; height: 50px; background-color: black;"></button>
<script type = "text/javacsript">
$(document).ready(function(){
$(".button").click(function(){
$("main").val("IT WORKED");
});
};
</script>
</html>

You forgot to use # for id selector, also use text() or html() instead of val() for div and you also missed the closing parenthesis of document.ready.
Live Demo
$(document).ready(function(){
$(".button").click(function(){
$("#main").text("IT WORKED");
});
});

Related

Toggle text inserted with innerHTML from Javascript

As an exercise I am trying to create a small quiz app and a part of it are the question cards. On these cards I have a question and then a button to show the answer. When the button is clicked, then the answer (which doesn't exist in the HTML DOM yet, therefore not visible) will show up and with the next click, the answer should be hidden again. Basically it will look something like this:
Before Show Answer is clicked
After Show Answer is clicked
Here is the HTML code:
<section class="question-card">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam vitae
labore repudiandae tenetur. Qui maiores animi quibusdam voluptatum
nobis. Nam aperiam voluptatum dolorem quia minima assumenda velit libero
saepe repellat. Tempore delectus deleniti libero aliquid rem velit illum
expedita nostrum quam optio maiores officiis consequatur ea, sint enim
cum repudiandae inventore ab nemo?
</p>
<div class="bookmark">
<i class="fa-regular fa-bookmark fa-lg"></i>
</div>
<button class="answer-button" data-js="answer-button">Show Answer</button>
<ul class="answer-container" data-js="answer-container">
</ul>
<div class="container-categories">
<button class="category-button category-html">#html</button>
<button class="category-button category-flexbox">#flexbox</button>
<button class="category-button category-css">#css</button>
<button class="category-button category-js">#js</button>
</div>
</section>
I have added an EventListener for the Show Answer button that adds a list item in the already existing ul when it is clicked. I have done this with innerHTML:
const answerButton = document.querySelector(".answer-button");
const answerContainer = document.querySelector(".answer-container");
const answer1 = "Lorem ipsum dolor sit amet consectetur adipisicing elit.";
answerButton.addEventListener("click", () => {
answerContainer.innerHTML = `<li class="show-answer">${answer1}</li>`;
});
Now what I can't seem to manage is to hide the answer when the button is clicked again (the next challenge will be that the button will change the text to "Hide Answer" after the first click, but I have no idea how to approach that yet). The closest I got was this:
answerButton.addEventListener("click", () => {
answerContainer.innerHTML = `<li class="show-answer">${answer1}</li>`;
answerContainer.classList.toggle("hide-answer");
});
However, this method displays the .hide-answer class first, after which the 2 classes are toggled and everything is as it should be. So after the first click, the answer is still hidden and only after the 2nd click the button behaves the way I want it to.
I have tried this as well:
answerButton.addEventListener("click", () => {
answerContainer.innerHTML = `<li class="hide-answer">${answer1}</li>`;
answerContainer.classList.toggle("show-answer");
});
But for some reason this shows the container with all the CSS properties, but there is no text:
Answer Container is there, but no text
This is the CSS for the 2 classes (show-answer and hide-answer):
.show-answer {
background-color: hotpink;
border-radius: 7px;
border: none;
list-style: none;
width: 50%;
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
box-shadow: rgba(0, 0, 0, 0.3) 0px 19px 38px;
}
.hide-answer {
display: none;
}
If anybody has any idea how I could get the result I need, I would be extremely grateful...
You're mixing up the answer-container with the answer-container's child (the innerHtml <li> element).
initially there's a visible, but empty <ul class="answer-container"></ul>.
Next on click of the button, you add the content into the answer-container expecting it to be visible with a show-answer class
Immediately after, you add the hide-answer class to the <ul class="answer-container"> parent element which hides the newly added content.
Click the button again and you finally see your answer because the container element has the hide-answer class toggled off. From here it works as you're expecting.
You can fix this by having the answer-container be hidden initially and then continue to toggle the display of the container. You can also just use a DOM element's hidden attribute to do this as I do in this code snippet below where I've taken your exact example and just modified the answer-container to start with hidden and toggle the hidden attribute on click. You can do the same thing w/ a CSS display: none class too.
const answerButton = document.querySelector(".answer-button");
const answerContainer = document.querySelector(".answer-container");
const answer1 = "Lorem ipsum dolor sit amet consectetur adipisicing elit.";
answerButton.addEventListener("click", () => {
answerContainer.innerHTML = `<li class="answer">${answer1}</li>`;
answerContainer.hidden = !answerContainer.hidden;
});
.answer {
background-color: hotpink;
border-radius: 7px;
border: none;
list-style: none;
width: 50%;
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
box-shadow: rgba(0, 0, 0, 0.3) 0px 19px 38px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<section class="question-card">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam vitae
labore repudiandae tenetur. Qui maiores animi quibusdam voluptatum
nobis. Nam aperiam voluptatum dolorem quia minima assumenda velit libero
saepe repellat. Tempore delectus deleniti libero aliquid rem velit illum
expedita nostrum quam optio maiores officiis consequatur ea, sint enim
cum repudiandae inventore ab nemo?
</p>
<div class="bookmark">
<i class="fa-regular fa-bookmark fa-lg"></i>
</div>
<button class="answer-button" data-js="answer-button">Show Answer</button>
<ul class="answer-container" hidden data-js="answer-container">
</ul>
<div class="container-categories">
<button class="category-button category-html">#html</button>
<button class="category-button category-flexbox">#flexbox</button>
<button class="category-button category-css">#css</button>
<button class="category-button category-js">#js</button>
</div>
</section>
Would something like this work?
You just use if the container has the class show-answer to determine if the answer needs to be shown or hidden
answerButton.addEventListener("click", () => {
if (answerContainer.classList.contains('show-answer')) {
// container has `showing` class
// hide the answer
answerContainer.innerHTML = ``; // ? - my guess, not sure how to want to hide it
}else{
// container doesn't have `showing` class
// show the answer
answerContainer.innerHTML = `<li class="hide-answer">${answer1}</li>`;
};
// update class
answerContainer.classList.toggle("show-answer");
});

Javascript page enter event

I want an event this should load everytime the site is typed in the browser example : http://localhost/ is typed in the url and the first page should show is my overlay. After they read the information they can close it but if they wanna read it again they can click the button. Also if the site is getting refreshed the overlay should be popup again.
My current code and where I stuck :
const doc = document;
const menuOpen = doc.querySelector(".menu");
const menuClose = doc.querySelector(".close");
const overlay = doc.querySelector(".overlay");
menuOpen.addEventListener("click", () => {
overlay.classList.add("overlay--active");
});
menuClose.addEventListener("click", () => {
overlay.classList.remove("overlay--active");
});
to do this in javascript you can achieve this using window.load like this:
window.onload = function() {myFunction()};
function myFunction() {
overlay.classList.add("overlay--active");
}
but for the best solution i would think adding the overlay--active by default as #Keith mentioned would be nicer as this requires less javascript for the webpage.
You could do it by using if-else structure in javascript. Like the code I posted here. In this method you don’t need the “onload” event. And the “overlay” popped up again when the page is refreshed.
var menuOpen = document.getElementById("menu");
var overlay = document.querySelector(".overlay");
menuOpen.addEventListener("click", () => {
if(overlay.classList.contains("active")){
overlay.classList.add("deactive");
overlay.classList.remove("active");
menuOpen.innerHTML = "show";
} else {
overlay.classList.add("active");
overlay.classList.remove("deactive");
menuOpen.innerHTML = "hide";
}
});
.active {
opacity: 1;
}
.deactive {
opacity: 0;
}
#menu {
margin-top: 15px;
margin-left: 100px;
width: 100px;
height: 60px;
background-color: #fff;
border: 1px solid #5522dd;
color: #5522dd;
cursor: pointer;
}
#menu:hover {
color: #fff;
background-color: #5522dd;
}
.overlay {
border: 2px solid #000;
margin-top: 25px;
-webkit-transition: 2s;
transition: 2s;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Javascript page enter event</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="overlay active">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui modi quasi, quam deleniti, placeat expedita nostrum quae quaerat? Id, velit iste saepe dolore, consequuntur vel quis iure excepturi ut aut fugit dignissimos ea magni repudiandae nihil, assumenda deleniti nostrum tenetur minima aperiam doloribus. Quaerat sunt nam distinctio! Suscipit nostrum vel, sunt, eos esse fugit.
</div>
<button id="menu">hide</button>
<script src="javasc.js"></script>
</body>
</html>
You can use jquery and use it in the loading of document.
like
document.ready(()=>{
$(".overlay").addClass("overlay--active");
})

How to create auto popup when I access a website

I was trying to create an auto popup when I access a web store that is developed in Shopif
<SCRIPT TYPE="text/javascript">
function popup(mylink, windowname) {
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string') href=mylink;
else href=mylink.href;
window.open(href, windowname, 'width=400,height=200,scrollbars=yes');
return false;
}
</SCRIPT>
<BODY onLoad="popup('autopopup.html', 'ad')">
I have the above code for Popup Windows Opening Automatically. However, I need assistance on how to make this work on and this is the website that I am trying to work it on https://petit-tapis.co.uk
Thank you in Advance
As #Scopey said, modern browsers prevent this behavior from auto occurring. You can however add a click or if you want people to take action first before doing anything else, you can for example add an overlay that blocks any other functionality (but I can tell you that this kills user experience).
Maybe say more what your goal is. Why do you want this extra window to open? What benefit is there in doing this (what do you and what does the user get out of it)?
edit: See my comment below. I also slapped together a very simple version of what I am talking about: https://jsfiddle.net/uthhvu8d/
HTML:
<div class="wrapper">
<div class="overlay">
<form action="">
<input type="text">
<input type="text">
<button>Submit</button>
</form>
</div>
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, inventore esse aliquam nostrum? Cupiditate provident, delectus, minus voluptatum natus fugiat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus temporibus vitae quibusdam maxime natus fugiat quis amet sed perferendis quod.</p>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam nostrum consequatur animi quod rem eos nihil obcaecati repellat. At, accusamus.</p>
</div>
CSS:
.wrapper {
position: relative;
}
.overlay {
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
color: #fff;
display: none;
}
JS:
function showOverlay() {
$('.overlay').show()
}
setTimeout(showOverlay, 2000)
Thankfully, modern browsers prevent this behaviour from happening.
Any window.open must occur only as a direct result of a user triggered event - such as a mouse click or similar.
As #Scopey said browsers stop you opening a pop up window however you could use the HTML5 Dialog and the dialog overlays in the browser have a play you can even open it model if you wanted will take a little longer to get it to work but it's anotion for you
<dialog id="dialog">
<iframe src="autopopup.html" />
</dialog>

drag and drop to contenteditable element second and subsequent lines

I want to drag and drop the tag to the contenteditable="true" element string using html5 and javascript.
<script>
window.addEventListener("DOMContentLoaded", function(){
function dragStartFromPalette(event){
event.dataTransfer.setData("text/html",
'<original-element class="draggable_element">'+this.innerHTML+'</original-element>');
}
function dragEndFromPalette(event){
event.dataTransfer.effectAllowed = "copyMove";
event.dataTransfer.dropEffect = "copy";
event.dataTransfer.getData("text/plain");
event.preventDefault();
}
var light_tags = document.getElementsByClassName('draggable_element');
for(i = 0; i < light_tags.length; i++){
light_tags[i].addEventListener('dragstart', dragStartFromPalette);
light_tags[i].addEventListener('dragend', dragEndFromPalette);
};
}, false);
</script>
<style>
.draggable_element {
background-color: rgb(251, 214, 132);
}
</style>
<original-element class="draggable_element" draggable="true">Lorem</original-element>
<original-element class="draggable_element" draggable="true">ipsum</original-element>
<original-element class="draggable_element" draggable="true">dolor</original-element>
<div contenteditable="true">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vel, illum reiciendis quas in quam eos iste inventore. Perferendis amet vel, ratione unde rerum? Quasi ea maxime incidunt, perferendis vero. Nesciunt.</div>
Here is my code https://jsfiddle.net/uzLb5xx0/
The first line will success. however, attempting to trying drag and drop to the second and subsequent lines will insert unrelated span element.
How can I insert all the elements as desired? help me ;(

Show one or more elements and their content that have been hidden

I'm stuck and not sure how to move on. I want to be able to click a tab to reveal its content. With the code I currently have, when I click a single tab, it reveals the content for all the tabs. But I just want the click to reveal the content that's associated with that single tab. I'm looking for a vanilla javascript solution.
Here's the code: http://codepen.io/anon/pen/KCJAc (inline below)
CSS:
.tab-content {
display: block;
height: 0;
opacity: 0;
overflow: hidden;
transition: all 1s ease-out;
}
.tab-active {
height: auto;
opacity: 1;
}
JavaScript:
var tabHeaders = document.getElementsByClassName('tab-header');
for (var i = 0; i < tabHeaders.length; i++) {
tabHeaders[i].addEventListener('click', activateTab);
}
function activateTab() {
var tabContents = document.getElementsByClassName('tab-content');
for (var i = 0; i < tabContents.length; i++) {
tabContents[i].classList.add('tab-active');
}
}
HTML:
<div>
<h3 class="tab-header">Tab1</h3>
<p class="tab-content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium odio iste aliquam molestias corporis blanditiis nihil soluta sint illum quibusdam reprehenderit sed quaerat iusto maiores error iure ducimus dicta ipsum.</p>
</div>
<div>
<h3 class="tab-header">Tab2</h3>
<p class="tab-content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium odio iste aliquam molestias corporis blanditiis nihil soluta sint illum quibusdam reprehenderit sed quaerat iusto maiores error iure ducimus dicta ipsum.</p>
</div>
You're adding tab-active to all of the tab-content elements. You just want to add it to the one following the header that's clicked: Updated Pen
var tabHeaders = document.getElementsByClassName('tab-header');
for (var i = 0; i < tabHeaders.length; i++) {
tabHeaders[i].addEventListener('click', activateTab);
}
function activateTab() {
var tabContents = this.nextElementSibling;
while (tabContents && (!tabContents.classList || !tabContents.classList.contains("tab-content"))) {
tabContents = tabContents.nextElementSibling;
}
if (tabContents) {
tabContents.classList.toggle("tab-active");
}
}
Notes:
I'm using nextElementSibling to get the next sibling that's an element since you used classList in the original, so I figure you're only using this code on fairly up-to-date browsers. If you intend to use it on older browsers, you can use nextSibling instead (and also use className rather than classList.
This is because by using document.getElementsByClassName you are getting all tab-content tabs in your page, rather than the DOM level of the clicked tab-header element. You can use the nextSibling property of tab-header to get the next DOM node beside tab-header:
function activateTab() {
this.nextSibling.classList.add("tab-active");
}
Or, if you are not sure if tab-content will definitely appear directly after tab-header you can query parentNode using querySelector:
function activateTab() {
this.parentNode.querySelector(".tab-content").classList.add("tab-active");
}
Note this last method won't work in anything lower than IE8, but then again neither will the classList property in your original question.

Categories

Resources