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>
Related
ref.Post Box Image
basically, I want to create this type of post box where user can customize their post.
but I don't know how to make it bold/italic/quote
I think you want to provide your users some standard form of text parsing, Markdown has the features you ask for.
You can try using a markdown parser like these:
marked (demo)
markdown-it (demo)
const textarea = document.querySelector('textarea');
const content = document.querySelector('.content');
const update = () => content.innerHTML = marked.parse(textarea.value);
textarea.addEventListener('input', update);
textarea.value = '**Bold** \n*Italic*'
update();
html,
body {
margin: 0;
height: 100%;
}
.container {
display: flex;
height: 100%;
}
.container>* {
flex: 1;
}
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<div class="container">
<textarea></textarea>
<div class="content"></div>
</div>
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>
I have a contenteditable tag, and I want my users to be able to type code into it. However, when I type into the contenteditable tag, my code shows up as text rather than an actual element. Is there a way for a user to create a full, working HTML element in a contenteditable box? I know it is possible for the client to insert code using javascript, but what about users who do not have access to javascript? How could users get code such as buttons inside a contenteditable box?
<p contenteditable="true">Try typing code in here as user, code will only be text...</p>
Is there a javascript way to accomplish this without JQUERY?
EDIT
I spent a long time searching for answers on Google, but nothing came up. The best solution I've gotten at this point has been #Dekel's comment on CKEditor. If there is another solution, I want to hear it. If there isn't, I'm sticking to CKEditor. I don't have much time, so I need a solution fast.
MORE EDIT =D
I recently developed my own answer to my question by looking at #Brandon's .replace answer (which only worked for client-coding, not user-coding) and modifying it to work with user-coding.
This isn't pretty, but you could make it work if you are looking to add HTML only. Otherwise an inline editor might work best.
var el = document.querySelector('p')
el.addEventListener('blur', function() {
var map = {amp: '&', lt: '<', gt: '>', quot: '"', '#039': "'"}
var html = this.innerHTML.replace(/&([^;]+);/g, (m, c) => map[c]);
this.innerHTML = html;
});
<p contenteditable="true">Try typing <b>code</b> in here as user, code will only be text...</p>
This answer is similar to #Brandon's idea, but is much more simple.
https://jsfiddle.net/azopqLe4/
<iframe width="100%" height="300" src="//jsfiddle.net/azopqLe4/embedded/js,html,result/dark/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
function convertit() {
var convet = document.getElementById("convet");
var text = convet.innerHTML;
var newtext;
newtext = text.replace(/</g, "<").replace(/>/g, ">");
convet.innerHTML = newtext;
}
//this version runs onrightclick =D
<p contenteditable="true" oncontextmenu="convertit();" id="convet">
Type some code here, then right-click... =D
</p>
In the second snippet, I typed <b>Test</b>, right-clicked it, and it became Test! My answer works through simple array replacement methods, although it is frustrating and time-wasting to keep right-clicking all the time. To prevent the actual contextmenu from popping up, just add .preventDefault().
You can't insert code, but you can insert DOMElements with JS. No need for jQuery.
var element=document.createElement("button");
element.innerHTML="Hello";
document.getElementById("yourContentEditable").append(element);
The idea with this would be to have a button to prompt for the code and insert it. Something like this:
(It is very ugly and buggy but it's just an example I just wrote)
var editorSelection=null;
function openCodePopup() {
//Store cursor position before editor loses focus
editorSelection=getEditorSelection();
//Open the popup
document.querySelector("#codePopup").style.display="block";
var ta=document.querySelector("#userCode");
ta.value="";
ta.focus();
}
function closeCodePopup() {
document.querySelector("#codePopup").style.display="none";
}
function insertCode() {
var code=document.querySelector("#userCode").value;
closeCodePopup();
if(code=="") return;
insertIntoEditor(html2dom(code));
}
function getEditorSelection() {
//TODO make crossbrowser
//TODO (VERY IMPORTANT) validate if selection is whitin the editor
var sel=window.getSelection();
if(sel.rangeCount) return sel.getRangeAt(0);
return null;
}
function insertIntoEditor(dom) {
if(editorSelection) {
editorSelection.deleteContents();
editorSelection.insertNode(dom);
} else {
//Insert at the end
document.querySelector("#editor").append(dom);
}
}
function html2dom(code) {
//A lazy way to convert html to DOMElements, you can use jQuery or any other
var foo=document.createElement('div'); //or you could use an inline element
foo.contentEditable=false;
foo.innerHTML=code;
return foo;
}
#editor {
height: 180px;
overflow: auto;
border: 1px solid #ccc;
}
#toolbar {
position: relative;
}
#codePopup {
position: absolute;
left: 10px;
top: 15px;
background-color: #fff;
border: 1px solid #ccc;
padding: 5px;
display: none;
}
#userCode {
display: block;
width: 200px;
height: 100px;
}
<div id="toolbar">
<button onclick="openCodePopup()"></></button>
<div id="codePopup">
<textarea id="userCode" placeholder="Type code here"></textarea>
<button onclick="insertCode()">Ok</button>
<button onclick="closeCodePopup()">Cancel</button>
</div>
</div>
<div contenteditable="true" id="editor"></div>
With the same idea you could create other options to convert element (example, text->link, etc.).
I have a question about how I can dynamically change a href="" in a button.
The jsfiddle below shows a button fixed at the bottom of the viewport starting at the landing page:
http://jsfiddle.net/Hm6mA/3/
The html of the button is like so:
<div class="button">
<a href="#first" class="" style="width: 80px; height: 80px; opacity: 1;">
<img src="img/down.png" alt="down">
</a>
</div>
When it is clicked I want it to scroll to the next section and change the href="" to the following section of the page. So, when it is first clicked, the href will change to #second. It would obviously also need to change when the user manually scrolls past a section.
This is for a single page website. How would I go about such a thing?
Use .prop() to change its value
$(".button").on('click', function(){
$('.button').find('a').prop('href', '#services');
});
Demo
You can use fullPage.js plugin to achieve what you want. Maybe it is faster than coding it from cero :)
Demo fullPaje.js
Page
I am not used to jquery. Here is a pure javascript solution. It surely changes the hash value.
<body>
<div id="sections">
<section id="s100">asdfasd</section>
<section id="s101"></section>
<section id="s102"></section>
<section id="s103"></section>
<section id="s104">asdfasdasdfsdf</section>
<section id="s105"></section>
</div>
<div class="nav-bar">
<a id="next-button" class="button" href="#s100">Next</a>
</div>
<script type="text/javascript">
var sections = document.getElementById("sections");
var nextButton = document.getElementById('next-button');
sections.onscroll = function (evt) {
}
var counter = 100;
var limit = 105;
// closure
nextButton.onmouseup = function (evt) {
var incCounter = function () {
// add your custom conditions here
if(counter <= limit)
return counter++;
return 0;
};
var c = incCounter();
if(c != 0)
this.setAttribute('href', "#s" + c);
}
</script>
</body>
CSS
html, body {
height: 100%;
width: 100%;
overflow: hidden;
}
#sections {
height: 50%;
width: 100%;
overflow: scroll;
}
.nav-bar {
margin: 30px 20px;
}
.button {
text-decoration: none;
border: 1px solid #999;
padding: 10px;
font-size: 120%;
}
I have written a small jQuery plugin for that, just pushed it to GitHub. https://github.com/ferdinandtorggler/scrollstack
What you basically want to do is calling
$('.button').scrollstack({stack: ['#first', '#second', ... ]});
You dont even need the link when you call it on the button. So check it out and let me know if it works for you. ;)
Here you can try it and read more: http://ferdinandtorggler.github.io/scrollstack/
I am building a web page and have run into something that would be nice to be able to do; set text to be copied to the clipboard when someone tries to copy an image, probably the same as the alt text. Is there any way with javascript/html that this can be done? If so, please explain.
Thanks for any help!
Edit: Basically, I want to let my users highlight the image, press control-c, and then have the alt text stored in their clipboard.
This is possible as Twitch.tv does this when copying emote images in chat. The trick is to use the copy event.
const parent = document.getElementById('parent');
parent.addEventListener('copy', event => {
let selection = document.getSelection(),
range = selection.getRangeAt(0),
contents = range.cloneContents(),
copiedText = '';
for (let node of contents.childNodes.values()) {
if (node.nodeType === 3) {
// text node
copiedText += node.textContent;
} else if (node.nodeType === 1 && node.nodeName === 'IMG') {
copiedText += node.dataset.copyText;
}
}
event.clipboardData.setData('text/plain', copiedText);
event.preventDefault();
console.log(`Text copied: '${copiedText}'`);
});
#parent {
display: flex;
flex-direction: row;
align-content: center;
align-items: center;
flex-grow: 0;
}
#parent,
#pasteHere {
padding: 0.5rem;
border: 1px solid black;
}
.icon {
width: 32px;
}
#pasteHere {
margin-top: 1rem;
background: #E7E7E7;
}
<p>Copy the line below:</p>
<div id="parent">
Some text <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg?v=f13ebeedfa9e" class="icon" data-copy-text="foo" /> some more text <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg?v=f13ebeedfa9e"
class="icon" data-copy-text="bar" />
</div>
<div id="pasteHere" contenteditable>Paste here!</div>
add attribute alt="text" to your image
example:
<img alt="🇫🇷" src="https://twemoji.maxcdn.com/v/14.0.2/72x72/1f1eb-1f1f7.png">
I don't think you can. If you could hook keyboard events through the browser, that'd be a tremendous security issue. You could capture keystrokes and send them to a web service in a few lines of code, which would ruin some lives pretty easily.
You may be able to detect a mouse down event using onmousedown by attaching it to the image in some fashion and store that alt-text in a hidden field or cookie and DoSomething() from there.
I've seen services such as tynt do something like this. 2065880 Javascript: Hijack Copy? talks about the techniques, as does 1203082 Injecting text when content is copied from Web Page