How can I insert an image on click in Javascript? - javascript

So I'm new to JavaScript and I have a list and when that list item is clicked, I want an image to appear, and only when it's clicked. How can I go about doing this through my JS document? I went ahead and made an ID for one of my list documents that I can use for my JS.
<div class="tab-pane active full" id="status" role="tabpanel">
<ul class="item-list">
<li><a id="pipboy_gun_img" href="#" class="44_pistol">.44 Pistol</a></li>
<li>10mm Pistol</li>
<li>Assault Rifle</li>
</ul>

In javascript, if you apply an event listener to a parent element, all the child elements of it are also listening to that event. So you can apply a click event to the <ul>. So all the <li> items are listening to that event.
Then use a switch case to switch between different click events.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script>
document.addEventListener('DOMContentLoaded' , function(){
var list = document.getElementById('allList');
var image = document.getElementById('targetImg');
list.addEventListener('click' , function(e){
switch(e.target.textContent){
case '44 Pistol':
image.setAttribute("src" , "https://www.pewpewtactical.com/wp-content/uploads/2019/12/8.-Glock-44-.22LR.jpg");
break;
case '10mm Pistol':
image.setAttribute("src" , "https://www.airgundepot.com/vault/wp-content/uploads/2016/08/Other-Pistol-Options.jpg");
break;
case 'Assault Rifle':
image.setAttribute("src" , "https://images-na.ssl-images-amazon.com/images/I/819LnIT7GSL._AC_SL1500_.jpg");
break;
default:
break;
}
})
})
</script>
<body>
<div class="tab-pane active full" id="status" role="tabpanel">
<ul class="item-list" id="allList">
<li><a id="pipboy_gun_img" href="#" class="44_pistol">44 Pistol</a></li>
<li>10mm Pistol</li>
<li>Assault Rifle</li>
</ul>
<img height="400px" width="400px" id="targetImg" src="" alt="">
</body>
</html>
side note: If you wondering what is this DOMContentLoaded, It prevents the javascript part is being executed before the HTML DOM is loaded.
If you don't want to use it just cut and paste <script> **your java script code ** </script> below the body tag.

Related

Avoiding Redundant Functions in Navigation Sidebar

I'm very new to web development stuff so I'm having trouble googling the correct terms here.
The sidebar navigation is working, but the scripts are ugly and redundant.
Is there a way to clean this up? Like store the link id and html file location in an array and just have one script that does the lookup?
I don't need "code for me", just a nudge in the right direction.
Example:
<!DOCTYPE html>
<html>
<link href="./styles/main_style_sheet.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#navigation_link_1').click(function(){
$('#content_area').load('location_1.html');
});
});
</script>
<script>
$(document).ready(function () {
$('#navigation_link_2').click(function(){
$('#content_area').load('location_2.html');
});
});
</script>
<script>
$(document).ready(function () {
$('#navigation_link_3').click(function(){
$('#content_area').load('location_3.html');
});
});
</script>
<script>
$(document).ready(function () {
$('#navigation_link_4').click(function(){
$('#content_area').load('location_4.html');
});
});
</script>
<body>
<div class="container">
<div id="concept-sidebar"">
<h4 style="text-indent: 0px;"> <strong> My Sidebar </strong></h4>
<div class="container" style="width:100%">
<div class="list-group">
<a id="navigation_link_1"
class="list-group-item custom"
> First Item </a>
<a id="navigation_link_2"
class="list-group-item custom"> Slowly Changing Dimensions (SCD) </a>
<a id="navigation_link_3"
class="list-group-item custom"> Important System Fields
</a>
<a id="navigation_link_4"
class="list-group-item custom"> Reference Data
</a>
</div>
</div>
</div>
</div>
</body>
</html>
There are multiple ways to solve this (and since you asked for a direction and not a solution I'll give give you a general instruction for one of the solutions:):
Instead of settings the click-event-handler on each element - select all the relevant elements and have a click event on all of them:
$('.list-group-item').click(function(){ ... })
The selection here is on all items that have the class list-group-item, which in your case is the <a> elements you are looking for.
Extract the relevant id from the <a> you have (for you can use regex for that, for example). Another option - use the data-* attribute and get the number from that attribute (<a data-id="1"> and $(el).data('id')).
Load the content based on the id you just got:
$('#content_area').load('location_' + id + '.html');

Getting the child img inside a div using $(this); [on click event]

I'm trying to get the child image of a clicked div.
I want to get it's src value. But it's returning undefined.
Could someone point me in the right direction?
Tried using Jquery .find() https://api.jquery.com/find/
Tried using Jquery .children() https://api.jquery.com/children/
Both return undefined.
for (let i = 0; i < $('#draw-raster > div').length; i++) {
$(document).on('click', '#raster-item'+i, () => {
let image = $(this).children('img').attr('src'); //undefined
let image2 = $(this).find('img').attr('src'); //undefined
if (image) {
console.log(image);
return alert("image child found!");
}
return setTimeout(() => {
$('#raster-item'+i).children('img').hide();
}, 4500);
});
$('#image'+i).hide();
}
load html:
for(let i = 0; i < 16; i++)
{
let image = displayImages();
$('#draw-raster').prepend(
"<div id=raster-item" + i + " class='imageh"+i+"' data-id=" + i + "><img src='"+ displayImages() +"' class='image "+i+"' id='image"+ i +"' alt='Failed to load image' width='173.19' height='107.3'></div>"
);
}
html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Memory</title>
<script src="inc/js/jquery.min.js"></script>
<link rel="stylesheet" href="inc/css/boostrap.min.css">
<link rel="stylesheet" href="inc/css/memory.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container justify-content-center">
<div class="wrapper">
<div class="row">
<div class="col-lg-9">
<div class="card">
<div class="card-header bg-dark" style="color:white;">
<h2>Memory</h2>
</div>
<div class="card-body">
<section class="col-12 mx-auto" id="draw-raster">
</section>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div class="card-header bg-dark" style="color:white;">
<h2>Turns</h2>
</div>
<div class="card-body">
<div id="turns">Turns: 0</div>
<div id="sets">Sets: 0</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-success col-12" type="button" id="reset">Reset scores</button>
</div>
</div>
</div>
</div>
</div>
<script src="inc/js/memory.js"></script>
</body>
</html>
Both attempts return undefined, i'm uncertain what would work.
Yes, I've been spamming google too. :'^)
A couple of notes on your code:
1) If you want to use this you'll need to switch from an arrow function back to a regular anonymous function. Arrow functions don't have a this of their own and will borrow the context from their outer lexical environment. It's why your code keeps return undefined.
2) You don't need a loop. The benefit of using jQuery is that you can operate on collections of elements all at once. In your case you're attaching a single event listener to a parent element (here: document) and waiting for events to bubble up from the .raster-item imgs and be "captured". This is called event delegation and is useful when you want to process new elements added to the DOM after it has loaded.
2) You will find it easier to use a class instead of many ids.
Here's an example based on your code with these changes:
// Use event delegation to add an event listener to the element with
// the container class that watches out for click events on **all**
// elements with the raster-item class that contain images
$('.container').on('click', '.raster-item img', function () {
// `$(this)` will be the image element, so simply grab its src
// from the attribute
console.log($(this).attr('src'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="raster-item"><img src="https://dummyimage.com/50x50/555/fff.png" /></div>
<div class="raster-item"><img src="https://dummyimage.com/50x50/777/fff.png" /></div>
<div class="raster-item"><img src="https://dummyimage.com/50x50/999/fff.png"/></div>
<div class="raster-item"><img src="https://dummyimage.com/50x50/bbb/fff.png" /></div>
</div>
You don't need jQuery for this. You can harness the power of event bubbling with vanilla JavaScript.
In the web page below, the code inside the script tags, listen for a click event and runs some code if that event happens, i.e. bubbles, through a DIV element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Clicked div img</title>
</head>
<body>
<div class="catcher">
<p>This is a div with an image inside</p>
<img src="image-to-pick.jpg" alt="image to pick" ()>
</div>
<script>
document.addEventListener('click', function (event) {
if (event.target.tagName == 'DIV') {
var imgToPick = event.target.querySelector('img');
console.log(imgToPick.src); // add your code here
}
}, false);
</script>
</body>
</html>
In other words, you trigger a "click event" whenever you click on that page, that event bubbles up until it reaches the root of the HTML document (which you can imagine as an upside-down tree where the root is the html tag).
If you don't need or don't want to let it bubble to the elements "above" you DIV, you can also stop the propagation of that click event by using event.stopPropagation(), right after you handle the img src.
You can find more info about how this works here on MDN (Mozilla Dev. Network)
I'm not quite sure in what context you need to do this, but with jquery it's pretty straight forward.
If you have multiple images within a parent div, you can set the child images as the selecters for the click event, and return each image src when clicked on directly.
The resulting jquery is only three lines long this way, and you can add as many images as you like to the parent div:
<div class="image-container">
<img id="first" src="first-source-goes-here.jpg" alt="img text" />
<img id="second" src="second-source-goes-here.jpg" alt="img text" />
<img id="third" src="third-source-goes-here.jpg" alt="img text" />
</div>
$(".image-container > img").click(function() {
// replace 'alert' with what ever you need it to be
alert( $(this).attr("src") )
})
EDIT:
In response to Andy's comment on my answer below, if you are loading images once the DOM has been loaded, then you could run a check on the click parent div to see if there are any images within it before returning the source:
$(".image-container").click(function() {
if( $(this).children("img").length > 0 ) {
alert( $(this).find("img").attr("src") )
} else {
alert('there are no images here')
}
})

JavaScript toggle one at a time

I need some help with toggling one question at time. I want to display one question and when I click the other question the old one will disappear.
Heading
Here is my code
I am not sure how to get them to show up one at a time I have tried many different ways and still haven't came up with anything.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>FAQs</title>
<link rel="stylesheet" href="main.css">
<script src="faqs.js"></script>
</head>
<body>
<main id="faqs">
<h1>JavaScript FAQs</h1>
<h2><a href="#" >What is JavaScript?</a></h2>
<div>
<p>JavaScript is a is a browser-based programming language
that makes web pages more responsive and saves round trips to the
server.
</p>
</div>
<h2>What is jQuery?</h2>
<div>
<p>jQuery is a library of the JavaScript functions that you're most
likely
to need as you develop websites.
</p>
</div>
<h2>Why is jQuery becoming so popular?</h2>
<div>
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>
</main>
</body>
</html>
:
"use strict";
var $ = function(id) { return document.getElementById(id); };
// the event handler for the click event of each h2 element
var toggle = function() {
var h2 = this;
// clicked h2 tag
var div = h2.nextElementSibling;
// h2 tag's sibling div tag
// toggle plus and minus image in h2 elements by adding or removing a class
if (h2.hasAttribute("class")) {
h2.removeAttribute("class");
} else {
h2.setAttribute("class", "minus");
}
//toggle div visibility by adding or removing a class
if (div.hasAttribute("class")) {
div.removeAttribute("class");
} else {
div.setAttribute("class", "open");
}
};
Do as follows:
Hide all the answers initially with CSS
Save questions and answers to the variables in JS file
Add function which is executed when any of the questions is clicked
Hide all the answers
Show the answer related to the clicked question
var questions = $("h2 a");
var answers = $("h2 + div");
questions.on("click", function(event) {
event.preventDefault();
var answer = $($(this).attr("href"));
answers.hide();
answer.show();
});
h2 + div {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main id="faqs">
<h1>JavaScript FAQs</h1>
<h2><a href="#q1" >What is JavaScript?</a></h2>
<div id="q1">
<p>JavaScript is a is a browser-based programming language
that makes web pages more responsive and saves round trips to the
server.
</p>
</div>
<h2>What is jQuery?</h2>
<div id="q2">
<p>jQuery is a library of the JavaScript functions that you're most
likely
to need as you develop websites.
</p>
</div>
<h2>Why is jQuery becoming so popular?</h2>
<div id="q3">
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>
</main>

Use jquery to set onfocus event for only img in <a</a> tags

I have this piece of code :
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<p class="demo">test </p>
<a href="xx" class="focusme">
<img src="images/testimage.gif" alt="" >
</a>
<a href="xx" class="focusme">
<img src="images/testimage.gif" alt="">
</a>
</div>
<script type="text/javascript" src="js/jquery.2.1.4.min.js"></script>
<script>
$(function () {
$(".focusme").focus(function(){
$(this).img.invert();
});
});
</script>
</html>
What I want to do is to invert the images when the <a> tag got focus, but I'm stuck to register the focus and blur event for them.
Here is what I'm trying to achieve :
for example, the html :
<a href="xx" class="focusme">
<img src="images/testimage.gif" alt="" id="img1">
</a>
So at this point, it's easy to access the img above because it has an ID :
$("#img1").invert();
but what i want is :
$(function () {
$(".focusme").focus(function(){
var img = $(this).img;
img.invert();
});
});
P/s : the invert() function is from a seperated js file, and is working well if I manually call it like this :
$("#img1").invert();
How can this be done?
Use the focus on <a> and use find() for the image
$(function () {
$("a.focusme").focus(function(){
$(this).find('img').invert();
});
});
The problem is that <img> tags cannot be focused by default. However, you can allow them to be focused by setting the tabIndex property.
$(".focusme").each(function(i) {
$(this).attr('tabIndex', i + 1)
})
After adding that, your code will be executed when you click on the images, and when you tab between them.
example: http://codepen.io/anon/pen/xZzzOm?editors=1010

How to submit a form when tab is click

I would like to submit a form, when a tab is clicked. This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit a Form on Tab Click</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style type="text/css">
</style>
<script>
$(function() {
$( "#Main" ).tabs();
});
</script>
<script>
$(document).ready(function(){
$('#Tab1').click(function(){
$('#Form_1').submit();
});
</script>
</head>
<body>
<div id="Main">
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
<li>Tab4</li>
<li>Tab5</li>
<li>Tab6</li>
</ul>
<form id="Form_1" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="1">
</form>
<div id="Tab1">
<p>Tab1</p>
</div>
<div id="Tab2">
<p>Tab2</p>
</div>
<div id="Tab3">
<p>Tab3</p>
</div>
<div id="Tab4">
<p>Tab4</p>
</div>
<div id="Tab5">
<p>Tab5</p>
</div>
<div id="Tab6">
<p>Tab6</p>
</div>
</div>
</body>
</html>
Each tab will submit a different form. I hope this helps to identify what I am trying to
achieve. I am new to all this so please be specific.
Thank you.
You can use this jQuery:
jsFiddle here
$(document).ready(function() {
$( "#Main" ).tabs();
$('[id^=ui-id-]').click(function() {
var tabId = $(this).attr('id');
alert('Tab clicked: ' + tabId );
if (tabId == 'ui-id-1') {
$('#LoginForm').submit();
}else if (tabId == 'ui-id-2') {
$('#form2').submit();
}else if (tabId == 'ui-id-3') {
$('#form3').submit();
}
});
});
jQueryUI tabs all have IDs beginning with ui-id-#, where # is the tab number (for example, ui-id-3.
The selector $('[id^=ui-id-]') means: For any element whose ID attribute begins with ui-id-, trap the click event and do this...
Note that the <form> tag must have an ID attribute, as specified in the above code. For example, for the form on Tab 3:
<form id="form3" action="whatever.php" method="POST">
Suppose each tab has a form on it and, for example, the forms all have IDs that are sequentially numbered according to the tab they are on, such as Form-1, Form-2, Form-5, etc. Then you could use the line var tabId = $(this).attr('id') to do this:
$(document).ready(function() {
$( "#Main" ).tabs();
$('[id^=ui-id-]').click(function() {
var tabId = $(this).attr('id'); //ui-id-4
var tabNum = tabId.split('-')[2]; //4
$('#Form-' + tabNum).submit();
});
});
For example, suppose the tab's ID is ui-id-4, then you would want to give the <form> for tab 4 an ID: <form id="Form-4">. The above code would then submit that form when the tab was clicked.
Note that the above code expects that your form tags will have an ID, such as:
<form id="myFormId" action="somepage.php" method="POST" >
Assuming your form will have an id of 'myform', you can put a click event listener on the tabs.
Add a class to your tabs class='tab'
$('.tab').on('click', function(){
$('#myform').submit();
});
The tabs widget has some events you can use. For example, when a tab is activated, you can have a handler for the activate event. You can use standard jQuery event handling, and specify the tabsactivate event. Something like this:
$('#Main').on('tabsactivate', function (event, ui) {
// your logic here
$('#someForm').submit();
});
You can inspect the ui argument passed to that event handler for information about the tab. For example, the specific tab being moved from/to. Like:
if (ui.oldPanel.selector == '#Tab1') {
// The user just left Tab1
}
So within that handler you'd perform whatever task you need to perform when a tab changes.
First each tab could have a reference to each form that must be submitted on tab click.
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
<li>Tab4</li>
<li>Tab5</li>
<li>Tab6</li>
</ul>
Then bind a click event to each tab:
$("#Main").on("click", "a", function() {
var formId = $(this).data("form");
$(formId).submit();
});
The easy way, asign an id attribute to each <a> and <form> and then do this:
<script type="text/javascript">
$(document).ready(function(){
$('#tab1').click(function(){
$('#form1').submit();
});
$('#tab2').click(function(){
$('#form2').submit();
});
$('#tab3').click(function(){
$('#form3').submit();
});
});
</script>
A fiddle example here

Categories