Jquery toggle through random div - javascript

I am new to jquery and am trying to code this for a class. I want to program a button that shows a random div paragraph that will disappear and be replaced by another when you click the button again.I am using three buttons to show things. Each button has four divs with the same class name and each has one paragraph in it. I tried using this code but it will show one paragraph and then add another under it. Another issue I'm having is that the button doesn't always work when I click it.The fourth button is for the user to input something that will be appended to each paragraph.
JQUERY
$(document).ready(function(){
$("#first").click(function(){
var random = Math.floor(Math.random()*5);
$(".firstin").eq(random).toggle();
});
$("#second").click(function() {
var random = Math.floor(Math.random()*5);
$(".secondin").eq(random).toggle();
});
$("#third").click(function(){
var random = Math.floor(Math.random()*5);
$(".thirdin").eq(random).toggle();
});
$("#button2").click(function(){
var place= $("#in").val();
if (place.length > 0){
$("div").append("<p> text" +place+ "</p>");
$("#in").val('');
}
});
});
HTML
<div class ="firstin">
<p>
text
<br>
text
</p>
</div>
</div><div class ="secondin">
<p>
text
<br>
text
</p>
</div><div class ="thirdin">
<p>
text
<br>
text
</p>
</div>
<button id = "first">Category1</button>
<button id = "second">category2</button>
<button id = "third">category3</button>
<input type = "text" id = "in" placeholder = "Text">
<button id = "button2">Text</button>
CSS
.first{ display:none;
}
</style>

Instead of this:
$("div").append("<p> text" +place+ "</p>");
append() adds whatever you have passed to it at the end of the element.
Use
$("div").html("<p> text" +place+ "</p>");
html() replaces the content inside

Related

Highlight Duplicate word on hover using javascript

I have the following html
<div class="my-div">
<p>
Hello from the moon
</p>
</div>
<div class="my-div">
<p>
Hello World
</p>
</div>
Is it possible using javascript that when I hover on the word 'Hello' in the first div, I highlight or even bold just the 'Hello' word in the second div..
Any help appreciated
To highlight a specific word you need to place it in <span> tag. For example:
<div class="my-div">
<p>
<span class="first-hello">Hello</span> from the moon
</p>
</div>
<div class="my-div">
<p>
<span class="second-hello">Hello</span> World
</p>
</div>
In JavaScript file, you can select your elements by using document.querySelector() function. And then add appropriate event listeners, in this case, mousemove that is fired when a mouse is moved while the cursor is inside the element, and mouseout that is fired when the cursor is moved outside of the element
const firstHello = document.querySelector(".first-hello");
const secondHello = document.querySelector(".second-hello");
firstHello.addEventListener("mousemove", () => {
secondHello.style.fontWeight = "bold";
});
firstHello.addEventListener("mouseout", () => {
secondHello.style.fontWeight = "normal";
});
I am using Lettering.js and Jquery to achieve this.
<script src="jquery-3.5.1.js"</script>
<script src="lettering.js"></script>
<script>
function btnClicked(){
//The words are now put into individual spans. See lettering js documentation
$(".lettr").lettering('words');
$("span").hover(function(e){
// set default background color to white
$("span").css("background-color", "white");
//Get the word at the current mouse hover
let word = e.target.innerHTML.trim();
//Keep a list of all spans in the html document
let listSpans = $("html").find("span");
//Loop through all the individual spans and see if the innerHTML matches the word. If so , highlight it.
for(let i=0;i<listSpans.length;i++){
let spanword= listSpans[i].innerHTML.trim();
if(spanword== word){
$(listSpans[i]).css("background-color", "yellow");
}
}
}, function (e) {
});
}
</script>
Here is my body
<body>
<div>
<p class="lettr"> Heloo i am </p>
<p class="lettr">Heloo me too</p>
</div>
<button onClick="btnClicked();">Click me</button>
</body>

How to change a string within a div that your selector is in with JQuery?

How do you change the name of text within a div that your selector is inside of? In other words, I'd like to click on a button and change the text of the text above the button (within the same div).
For example, in my html, there is a button and a title above it. Once the button is clicked, I'd like the title above it to change to the id of the button.
This problem is similar to this question, but I'm having difficulty changing the text within the div that the selector is in.
Below is my attempt to grab the id of the button, and change the text within the div container.
Javascript (my attempt) (codepen here):
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id')
$('#title').find($(this)).html(desired_name);
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p id="title">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name1">NAME</button>
</div>
<div>
<p id="title">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name2">NAME</button>
</div>
Have you tried $(this).siblings("p")
This will select the <p> above the button
Have you tried jquery .prev()
https://api.jquery.com/prev/
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id')
$(this).prev().html(desired_name);
});
You can use the jQuery method siblings() to select the <p> element inside your <div> container.
However I recommend using a class as a unique selector inside your container.
$('.btn.btn-default').on('click', function() {
$(this).siblings(".desired-name").text($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="desired-name">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name1">NAME</button>
</div>
<div>
<p class="desired-name">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name2">NAME</button>
</div>
Change the ID's to classes for starters. Then target them like this:
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id');
$(this).prev(".title").text(desired_name);
});

Apply superscript to the selection using JavaScript

Can any one help me how can I apply superscript to the selection in my content editable div using javascript?
I have this div and a button:
<div contenteditable="true">Apple Grapes Orange</div>
<input type="button" onclick="applySuperScript" value="Apply SuperScript">
Suppose if I have selected the text "Orange" from my content editable div and click on button, javascript should be called to apply super script for the text "Orange".
Slight modification to the html.
<div id='text' contenteditable="true">Apple Grapes Orange</div>
<input type="button" id='super' value="Apply SuperScript">
This is our click handler
document.getElementById('super').onclick = function() {
var textarea = document.getElementById('text');
var anchorOffset = window.getSelection().anchorOffset;
var focusOffset = window.getSelection().focusOffset;
var str = textarea.innerHTML.substring(anchorOffset,focusOffset)
textarea.innerHTML= textarea.innerHTML.replace(str,'<sup>'+str+'</sup>');
};
Here is the fiddle.

How to access appended element and remove it?

I've done quite a bit of research for this but can't get my mind around it.
There is a parent div .container. Which has numerous child divs having different text inside them. There are two buttons outside the .container. One is used to dynamically create and append a child element having particular text. Other is to remove a child div having particular text.
The first time the page is loaded everything works but when a new child div is added (lets say having text xyz) and then use enters xyz in textarea and presses remove button (which is coded to remove child div having text xyz in them) it doesn't work.
Sample HTML markup (there may be infinite number of child divs)
<div class="container>
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
<div class="child4"></div>
</div>
<button class="AppendWithSomeText"></button>
<button class="RemoveDivWithSomeMatchedText"></button>
<textarea></textarea>
jquery for adding the div
var newdiv = = document.createElement('div');
newdiv.className = 'child';
$(".container").append(newdiv);
$(".container").find(".child").html(textfromtextarea);
// here text from text area is a string stored from user input in textarea
jQuery for remove button
$('.container>div:contains("'+textfromtextarea+'")').remove();
//works only first time
http://codepen.io/dustinpoissant/pen/VYXGwB
HTML
<input type='text' id='input' />
<button onclick='addItem()'>Add</button>
<button onclick='removeItem()'>Remove</button>
<br><br>
<div id='box'></div>
JavaScript
function addItem(){
$("#box").append("<span>"+$("#input").val();+"</span>");
}
function removeItem(){
var text = $("#input").val();
$("#box span").each(function(i, el){
if($(el).text()==text) $(el).remove();
});
}
Inorder to keep the uniformity of structure I have added class of type child-number.
I hope this is what you expected.
$(document).ready(function() {
$(".AppendWithSomeText").on("click", function() {
$(".container").append("<div class=child" + ($("[class^='child']").length + 1) + ">" + $(".content").val() + "</div>")
})
$(".RemoveDivWithSomeMatchedText").on("click", function() {
$('.container>div:contains("' + $(".content").val() + '")').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<div class="child1">somecontent</div>
<div class="child2">somecontent</div>
<div class="child3">somecontent</div>
<div class="child4">somecontent</div>
</div>
<button class="AppendWithSomeText">add</button>
<button class="RemoveDivWithSomeMatchedText">remove</button>
<textarea class="content"></textarea>

JavaScript - change value of button when text is selected within a DIV (and combine it in one simple function)

I have two simple JavaScript functions: getSelectedText() and doSomethingWithSelectedText() that I found in a different example.
Now I've adjusted it more to my needs: http://jsfiddle.net/83T7U/.
The example currently works but not the way it should. Currently, when text is selected, there is an alert(), but instead the text on button should change from Reply to Quote.
So, instead:
alert("Text selected - it should change "Reply" to "Quote" text button ONLY if text was selected within one of these DIVs and text should change only in the div within which the text was selected.");
It should be like document.getElementsByTagName("button") or similar.
My goal is to:
Change the value of the button from Reply to Quote as soon as text from a particular div is selected. When the text is de-selected, then button should change back to Reply.
Make sure the Reply<>Quote change applies only when text is selected within one of these DIVS (and not in other parts of the page).
Minimize the functions - I think instead of the two functions one is enough because I don't want to know the value of selection - I just want to check if there is something (ie. at least one character) selected/highlighted.
The JavaScript should work correctly with all the major browsers.
Please note I cannot use jQuery here. Thank you!
HTML:
<div id="first" style="background:yellow">DIV1: First some test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<div id="second" style="background:green">DIV2: Second some test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<div id="third" style="background:lightblue">DIV3: Third some test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<i>(there could be more similar divs on a page)</i>
JavaScript:
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
function doSomethingWithSelectedText() {
var selectedText = getSelectedText();
if (selectedText) {
alert("Text selected - it should change Reply to Quote text button ONLY if text was selected within one of these DIVs and text should change only in the div within which the text was selected.");
}
}
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
Look at this fiddle
with following html (yours with additional class for divs):
<div id="first" class="specialDiv" style="background:yellow">DIV1: First some test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<div id="second" class="specialDiv" style="background:green">DIV2: Second some test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<div id="third" class="specialDiv" style="background:lightblue">DIV3: Third some test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<i>(there could be more similar divs on a page)</i>
and the javascript:
function doSomethingWithSelectedText() {
//relabel quoteButton to standard-label
var buttons = document.getElementsByClassName('quoteButton');
if(buttons.length){
var button = buttons[0];
button.innerHTML = 'Reply';
var classArr = button.className.split(' ');
classArr.splice(classArr.indexOf('quoteButton'), 1);
button.className = classArr.join(' ');
}
//check if new quoteButton should be labeled
if (window.getSelection && window.getSelection().toString()) {
if(window.getSelection().anchorNode.parentNode && window.getSelection().anchorNode.parentNode.className && window.getSelection().anchorNode.parentNode.className.split(' ').indexOf('specialDiv') > -1){
var button = window.getSelection().anchorNode.parentNode.getElementsByTagName('button')[0];
button.innerHTML = 'Quote';
button.className += ' quoteButton';
}
}
}
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
In this article is mentioned to get the element that is selected by window.getSelection().anchorNode.parentNode. So I simply let check if the selected element has the newly added class 'specialDiv'. If it has search for the button and relabel it. Additonaly add a class to the button to be able to find relabeled buttons again. At any selection let the button be reset to the standard label, before maybe relabeling other buttons.
EDIT :
It's a little sad but there's one way the solution above wont work: Selecting text and then clicking into it. Thats the only way that at the timepoint of mouseup-event the old selectedText is still set (and will be unset immediatly after mouseup-event).
To fix this use onclick instead of onmouseup
Look at this fiddle... it uses onclick instead of of keyup since click will be triggered at a timepoint at that the new selection has been set in any case
Try following example. I hope it will help you. To try following example just copy following code and pest it in blank notepad and save it with .html extension and run it in any browser.
<html>
<head>
<style>
.head {
border:1px solid #666;
background-color:#f0f0f0;
padding:3px;
cursor:pointer;
}
.content {
border:1px solid #666;
background-color:#fff;
height:100px;
padding:3px;
}
</style>
<script type="text/javascript">
function getSelectedText(i) {
var pi = document.getElementById("pi").value;
var str = window.getSelection();
if(str!="") {
if(pi=="") {
document.getElementById("btn"+i).value="Quote";
}
else {
document.getElementById("btn"+i).value="Quote";
document.getElementById("btn"+pi).value="Reply";
}
}
else {
document.getElementById("btn"+i).value="Reply";
document.getElementById("btn"+pi).value="Reply";
}
document.getElementById("pi").value = i;
}
</script>
</head>
<body>
<div>
<div id="head1" class="head">Head 1</div>
<div id="content1" class="content" onMouseUp="getSelectedText('1')">Content 1 Div. Select text in this div.</div>
<input type="button" id="btn1" value="Reply" />
<div id="content2" class="content" onMouseUp="getSelectedText('2')">Content 2 Div. Select text in this div.</div>
<input type="button" id="btn2" value="Reply" />
</div>
<input type="hidden" id="pi" name="pi" value="" />
</body>
</html>

Categories

Resources