I am trying to display different prices for a single product on a generic /eu/ webpage. The prices are fixed so I am hoping this can be done using a simple query but I am very new to JS/JQuery.
Currently the price is displayed in div with the class price-block
and users can toggle their locale with a data-locale="{country code}" div.
Using these two IDs, can I create a script that says e.g. data-locale="UK" then price is £1000?
I think I need to be looking into "if this selected, var equals this value" solutions - any help much appreciated.
Here's one way of achieving it by using a simple key/val object for locale/price respectively:
$(function() {
var prices = {
"UK": "£1000",
"US": "$1500",
"DE": "€1250"
}
$("[data-locale]").click(function() {
var locale = $(this).attr("data-locale");
// ensure the locale value is valid
if (prices[locale]) {
$(".price-block").text(prices[locale]);
} else {
$(".price-block").text("Invalid locale: " + locale);
}
})
})
[data-locale] {
border: 2px solid;
cursor: pointer;
display: inline-block;
padding: 5px;
}
.price-block {
font-size: 20px;
margin-top: 10px;
}
<div class="locale-block">
<div data-locale="UK">UK</div>
<div data-locale="US">US</div>
<div data-locale="DE">DE</div>
</div>
<div class="price-block"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
so I finished a coding bootcamp a little while ago and I'm still pretty novice to Javascript. I'm having issues finding a solution to creating dynamic code. Basically I have an email Icon under every employee on the team and when hovering over the icon I want it to show their email. I can hard code this but we have multiple team pages with a different amount of employees on them.
<div class="member">
<img class="member-img" src="/assets/images/signage/example.png" alt="">
<h5 class="member-details">example</h5>
<img onmouseover="showEmail()" onmouseleave="hideEmail()" class="email-icon" id="emailIcon2" src="/assets/images/email-asset-128-fix.png" alt="">
<h5 class="email-txt" id="emailTxt">example#email.com</h5>
</div>
Specifically on this page I have 3 other of these divs for each team member. I have put both the Icons and Email texts h5s into arrays with the code below.
const allIcons = [];
$('.email-icon').each(function() {
allIcons.push(this);
});
console.log(allIcons);
const allEmails = [];
$('.email-txt').each(function() {
allEmails.push(this);
})
console.log(allEmails);
Being newer to Javascript I'm struggling to figure out what I should do here and I can't find a similar solution to this online. I want it be when I hover over Icon 1 it shows Email 1 and so forth, same goes for onmouseleave I just want to hide the h5 again. My css for the email-text is below.
.email-txt {
color: #474747;
margin: 0;
padding: 3px;
transform: translateY(-260%);
border-style: solid;
border-radius: 5px;
border-color: #474747;
background-color: darkgray;
color: black;
display: none;
}
I've tried this solution Change Color of Icon When Hovering Over Adjacent Text With jQuery
I don't know if I'm just not doing it right or what but can't get it to work.
Feel free to judge my code too, the more advice the better :). Thanks!
Assuming that the email addresses are in an array, all you need to do is generate a new image with its title attribute set to the email address for each array entry:
["1#2.com", "3#4.com", "4#5.com", "5#6.com"].forEach(function(item){
let link = document.createElement("a"); // Create dynamic anchor
link.href = "mailto:" + item; // Set link to go to array item
let img = document.createElement("img"); // Create dynamic image
img.alt = item; // Set the required alt attribute
img.src = "https://illustoon.com/photo/dl/2751.png"; // Set image source
img.title = item; // Set the tooltip for the image to the array item
link.append(img); // Put the image in the anchor
document.body.append(link); // Put the anchor on the page
});
img { width: 30px; }
<p>Hover over each icon to see the email address
NOTES:
Don't store HTML elements in an array - - they are already in the DOM so there's no reason to maintain a second list of them. Just store the data you want to work with in the array.
Don't use headings (<h1>...<h6>) because of how the text is styled by the browser. Headings are to define document structure and are essential for those who use assistive technologies (like screen readers) to browse the web. An <h5> would only ever be used to sub-divide an existing <h4> section. And an <h4> should only be used to sub-divide an <h3> section, and so on.
You are using JQuery in your code. While there's nothing inherently wrong with JQuery, it's widely overused to solve simple coding scenarios. Your situation here is very simple and really doesn't warrant JQuery. Learn JavaScript very well before learning JavaScript libraries and frameworks.
You could use CSS to handle the hovering effect, when possible CSS is preferrable over JS to handle these scenarios:
const employees = [{
email: "member1#email.com",
img: "👮"
}, {
email: "member2#email.com",
img: "👷"
}, {
email: "member3#email.com",
img: "💂"
}, {
email: "member4#email.com",
img: "🕵"
}]
employees.forEach(d => {
const html = ` <div class="member">
<div class="member-img">${d.img} </>
<h5 class="member-details">${d.email.match(/.*(?=#)/)}</h5>
<div class="email-icon">✉️<h5 class="email-txt" id="emailTxt">${d.email}</h5></div>
</div>`
root.innerHTML += html
})
#root {
display: flex;
justify-content: center;
}
.member {
display: flex;
flex-direction: column;
align-items: center;
}
.email-icon {
position: relative;
font-size: 3rem;
cursor: pointer;
}
.email-txt {
display: none;
position: absolute;
top: 0;
left: 0;
transform: translateX(-50%);
}
.email-icon:hover .email-txt {
display: block;
}
<div id="root"></div>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have been having a lot of problems with section of code, just as I thought it was all working great I find there is a new problem. It is part of a chat script and this section outputs the final code to div /div but the output is not what is expected. I am trying to implement a button where when it is pressed it will prompt a user to enter a valid youtube video URL, it is then sent to the Node.js server and then sent back to the browser. When I console.log the incoming data to the browser, it is what I was expecting.
The problem is After the data is sent to the function myChat(bubble), the youtube link and div contents look as though they have already been parsed and displays just a white box where the video should be.
I have shortened the code below removing code which is not needed for an example.
sock.onmessage = function(event){
var json = JSON.parse(event.data);
const key = json.name;
if(key) {
if (key === "Server"){
var bubble = '<div class="bubble-container"><span class="server"><div class="bubble-text"><p><strong><'+json.name+'></strong> '+json.data+'</p></div></div>';
}else{
const zKey = json.lock;
var bubble = $('<div class="bubble-container" id="'+json.name+'"><span class="bubble"><div class="bubble-text" id="'+zKey+'"><p><div class="close-x" onclick="DelBubble(event, urank)"></div><strong> <'+json.name+'></strong> '+string+'</p></div></div>');
}
myChat(bubble);
}
}
function myChat(bubble){
$("#msgText").val("");
$(".bubble-container:last").after(bubble);
if (bubbles >= maxBubbles) {
var first = $(".bubble-container:first").remove();
bubbles--;
}
bubbles++;
$('.bubble-container').show(250, function showNext() {
if (!($(this).is(":visible"))) {
bubbles++;
}
$(this).next(".bubble-container").show(250, showNext);
$("#wrapper1").scrollTop(9999999);
});
};
I have tried everything I can think of and have now run out of ideas. All I want is the string to output the same as it was entered by the user.
A few things:
You use var in a very confusing and bad way. Use let instead.
Your bubble var is one time filled with a string and another time with a jQuery element
Your bubble content strings have an unequal amount of opening and closing tags. Check your HTML
We can't comment on things we can not see, like #msgText, either include them or exclude them completely
Your code probably does not work because of some mistake in the areas we cant comment on. Check my snippet to see that it works
const bubble = `<div class="bubble">
<strong><${'TEST'}></strong>
${'https://www.youtube.com/watch?v=oHg5SJYRHA0'}
</div>`;
$(".bubble:last").after(bubble);
#test {
width: 100%;
height: 100%;
border: 1px solid red;
}
.bubble {
width: 100%;
height: 20px;
border: 1px solid black;
margin-top: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
<div class="bubble">
<strong><USER1></strong>Message text
</div>
</div>
As you requested a solution to show the video directly in the chat, here is a message with an embeded video player:
const embedMessage = (user, message) => {
let bubble;
if(message.includes('https://www.youtube.com')) {
bubble = `<div class="bubble">
<strong><${user}></strong>
<iframe width="200" height="100"
src="${message}"></iframe>
</div>`;
} else {
bubble = `<div class="bubble">
<strong><${user}></strong>
${message}
</div>`;
}
$(".bubble:last").after(bubble);
}
embedMessage('USER1', 'Send me the video!');
embedMessage('USER2', 'https://www.youtube.com/watch?v=oHg5SJYRHA0');
#test {
width: 100%;
height: 100%;
border: 1px solid red;
}
.bubble {
width: 100%;
border: 1px solid black;
margin-top: 3px;
padding: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
<div class="bubble">
<strong><USER1></strong>Message text
</div>
</div>
I'd like to create a product feature selection page where the user needs to select 3 features out of 6. Now, I got to a point where I can limit the number of selectable elements so if 3 elements are selected, the user wont be able to select a 4th one.
I need to modify this so when the user is attempting to select the 4th element, the 1st element they selected becomes unselected and the 4th element becomes selected. I hope it makes sense.
$('div').click(function(e) {
var $et = $(e.target);
if ($et.hasClass('fill')) {
$et.removeClass('fill');
} else {
if ($('.fill').length < 2) {
$et.addClass('fill');
}
}
});
div {
border: 1px solid blue;
height: 25px;
margin-bottom: 5px;
}
.fill {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>
<div id="4">four</div>
This fiddle shows where I'm at with my code: http://jsfiddle.net/MarKP/32/
This fiddle is not mine, but this is exactly what I have right now in my project.
I'm trying to get this done using jQuery or plain JavaScript.
Thank you in advance!
To achieve this you can maintain an array which holds the order in which the elements were clicked. Then, when the limit is hit, you can remove the class from the element which was selected first. Try this:
var selections = [];
var $div = $('div').click(function(e) {
selections.push(this.id);
if (selections.length > 3)
selections.shift(); // remove first item
setState();
});
function setState() {
$div.removeClass('fill');
$div.filter(`#${selections.join(',#')}`).addClass('fill');
}
div {
border: 1px solid blue;
height: 25px;
margin-bottom: 5px;
}
.fill {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>
<div id="4">four</div>
<div id="5">five</div>
<div id="6">six</div>
Finally, note that jQuery 1.4.4 is massively outdated; nearly 10 years in fact. You need to update it.
I have an html file(a webpage). I want when I press a button on it, the page should be replaced by another html file (with its own css, javascript functions etc) without being redirected to some other link.
For example, if link in first case is abc.com/def it should be same after too.
Using this code, I am able to change webpage look, but not getting how to change look (and also manage to load css and js functions) from another file.
<script type="text/javascript">
document.body.addEventListener('click',function(){
document.write("THIS IS NEW TEXT")
},
false);
</script>
You need to look into frameworks like AngularJS, Specially Routing of Angular. They provide such features built-in for web applications. However, you can do it the hard way, using javascript, like you are doing it right now. Add CSS and change whole body HTML using javascript if you don't want to learn any new framework or libraries.
You want to use PJAX,
Here's a link for an example.
As discuss by others, you should use a Framework to do this..
But this is a complete solution you can inspire of:
let layouts = {}
let current = null
// Display the new page by deleting current, and replacing by the good one
let displayLayout = (layout_id) => {
let parentNode = current.parentNode
parentNode.removeChild(current)
current = layouts[layout_id]
parentNode.appendChild(current)
loadEvents(current)
}
// Load event for HTML DOM you just created
let loadEvents = (layout_el) => {
Array.from(layout_el.getElementsByClassName('go-to-layout')).forEach(el => {
el.addEventListener('click', e => {
e.preventDefault()
displayLayout(e.currentTarget.dataset.layout)
})
})
}
// On init I get all the existing layout, but you can build you own dictionary an other way.
Array.from(document.getElementsByClassName('layout')).forEach(l => {
layouts[l.id] = l
if (l.classList.contains('active')) {
loadEvents(l)
current = l
}
else {
l.parentNode.removeChild(l);
}
})
/* Global CSS */
body, html, .layout {
height: 100%;
margin: 0;
}
* {
color: #FFF
}
.layout {
display: flex;
}
.nav, .page {
}
.nav {
width: 150px;
background: #555;
}
/* Special CSS for one layout */
#layout1 {
background: red;
}
#layout2 {
background: blue;
}
<div id="layout1" class="layout active">
<div class="nav">
Page 2
</div>
<div class="page">
This is page 1
</div>
</div>
<div id="layout2" class="layout">
<div class="nav">
Page 1
</div>
<div class="page">
This is page 2
</div>
<style>.page { font-size: 2em }</style>
</div>
I'm new to coding, I've learned the very basics of html/css/js/java, at least I thought I had, until I went to make a simple game.
I made a simple choose your own adventure game that worked, as each choice just went to a new page.
Then, I thought I'd make it a bit more complex, so I want to have the user enter their name, and store that to show next to the player's stats.
I've got a dropdown box with 4 choices for characters.I want to have Strength/Mana/Lives stats and have the player's choice of character to be able to adjust these stats accordingly before the game starts i.e. Male Warrior would have 2 extra Strength, Female Mage 2 extra mana etc.
Then, I'd like an image based on their character choice displayed next to their stats, so that the game can begin.
So far, I've been pulling my hair out in great clumps and have tried many different methods but so far, I've only got to the stage where I place the page with user input into an iframe. I can get to reflect their choices with text, but I can't get an image to load on submit. Ideally I'd like a permanent box in the top corner of the iframe, and have the statistics variables passed into the stats shown alongside the character's image.
I'd really really appreciate any help here, especially if it can be solved using HTML/CSS/JS as I'm not too familiar with JQuery, and would like to keep it as simple as possible really.
I've gone through as many q's and a's as I can to find relevant help, but I'm mainly finding answers for PHP or other languages.
I must apologise in advance for my waffling above, and sloppy coding. (I seriously thought this would be easy heh).
I'm unsure if my code so far will help, but I'll just paste it below anyway.
HTML for the UI page is:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Character Selection</title>
<link rel="stylesheet" href="css/style2.css">
<style>
img {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<div>
<div id='gamestitle'>
<p>
<img src = "GAMETITLE.jpg"
alt = "Steve's Perilous Capers"/>
</p>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLable' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p></div>
</div>
<div>
</div>
<div>
<form>
Select your Hero please:
<select id="mySelect">
<option>Male Warrior</option>
<option>Male Mage</option>
<option>Female Warrior</option>
<option>Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<script src="js/index.js"></script>
<script>
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
</script>
<p id="demo"></p>
</body>
</html>
The CSS is:
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide { display: none;}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
The JS file: (I've tried using icons and background image but I couldn't get them to show)
// the function which handles the input field logic
function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');
if (nameField.length < 3) {
result.textContent = 'Username must contain at least 3 characters';
//alert('Username must contain at least 3 characters');
} else {
result.textContent = 'Your Hero is: ' + nameField;
//alert(nameField);
}
}
function getOption() {
var obj = document.getElementById("mySelect");
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
}
function swapImage(){
var image = document.getElementById("imageToSwap");
var dropd = document.getElementById("dd");
image.src = dropd.value;
};
// use an eventlistener for the click event
var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false);
var subButtonTwo = document.getElementById('subButtonTwo');
subButtonTwo.addEventListener('click', getOption, false);
$(function () {
$.widget("custom.iconselectmenu", $.ui.selectmenu, {
_renderItem: function (ul, item) {
var li = $("<li>"),
wrapper = $("<div>", {text: item.label});
if (item.disabled) {
li.addClass("ui-state-disabled");
}
$("<span>", {
style: item.element.attr("option-style"),
"class": "ui-icon " + item.element.attr("data-class")
})
.appendTo(wrapper);
return li.append(wrapper).appendTo(ul);
}
});
$("#mySelect")
.iconselectmenu()
.iconselectmenu("menuWidget")
.addClass("ui-menu-icons avatar");
});
/*
function getcurrentChoice() {
var characterSelection = ['MaleWarrior'], ['MaleMage'], ['FemaleWarrior'], ['FemaleMage'];
var currentChoice = document.getElementById('currentChoice').value;
var resultChoice = document.getElementById('resultChoice');
var subButtons = document.getElementById('subButtons');
subButtons.addEventListener('click', getcurrentChoice, false);
}
*/
Sorry for the messy coding, it's not helped that I've tried so many workarounds for each problem I've encountered that I've lost track of what is and isn't working.
I'm pretty sure this is out of control by now, and a waste of your time, but I'm so confused. I'm sure i'm over complicating the matter.
Thanks in advance again,
Steve.
Check this:
https://jsfiddle.net/digitalrevenge/q9z1x6vv/
I've added an img src and made some changes to your JS.
I'm not sure if it does exactly what you want but there's no harm in giving it a try ;)
I am not sure how to do this in Javascript, but I have achieved it with jQuery, maybe you can adapt it to Javascript if you like.
Basically...
Give each option a value
On selection, or change, empty div#change_this, and check for the value
If value = # then add html code to div#change_this
You can change the image/add in the stats, I just used some filler.
You will also need to add css and all that, if you have any specific questions about that, please let me know.
Functionality is there though.
Best,
Levi
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide {
display: none;
}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
<div>
<div id='gamestitle'>
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLabel' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p>
</div>
</div>
<div>
<form>
Select your Hero please:
<select name="hero_type" id="mySelect">
<option value="0">Male Warrior</option>
<option value="1">Male Mage</option>
<option value="2">Female Warrior</option>
<option value="3">Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<div id="change_this">
<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('select[name="hero_type"]').click(function() {
$('#change_this').empty();
if ($('select[name="hero_type"]').val() == "0"){
$('#change_this').append('<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "1"){
$('#change_this').append('<p>Yayyy, Male Mage.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "2"){
$('#change_this').append('<p>Yayyy, Female Warrior</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "3"){
$('#change_this').append('<p>Yayyy, Female Mage</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
})
});
</script>
The src attribute of an image tag points to the location of the image file to use.
You should be somewhat aware of this as your code contains:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
To change the image, simply change the src attribute to point to the location of the new image.
The source of an image tag can be accessed and changed via:
document.getElementById("imageId").src="fileToUse";
This means you need to add an id to your image tag as so:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers" id="imageId"/>
In your case, you want to get the image src from a select field. This means you need to tie the image file locations to your select form as values.
<select id="mySelect">
<option value="location-of-this-image.png">Male Warrior</option>
<option value="location-of-this-image.png">Male Mage</option>
<option value="location-of-this-image.png">Female Warrior</option>
<option value="location-of-this-image.png">Female Mage</option>
</select>
To use these values and assign them to the image src:
document.getElementById("imageId").src=document.getElementById("mySelect").value;
If you correctly id your image and select form, give the select form proper values, and put the above line of code in the function you call when choosing and image, your image should change.
Important Note
JQuery is a JavaScript library and isn't part of the base language. To use JQuery, you must import it in your html code. You seem to be using JQuery functions, but I don't see where you imported JQuery. This may be causing you problems/breaking your code.
If you do have JQuery imported, the above code can be rewritten using JQuery rather than vanilla JavaScript and it'll look a lot cleaner.