Jquery hide text outside block - javascript

I am fairly new to Javascript and am trying to write an extension for Chrome. I am struggling with one aspect. Please note that the HTML comes from another webpage over which I have no control so I cannot modify it unless I do it programmatically. Also, I have shown three text items in the example below, but this could be as few as one or many more separated by "br". The HTML is as below:
<div class = "cls" id = "1234">
<quote>...</quote>
"Text to hide/show 1"
<br style="font-size: medium; height: auto; line-height: normal;">
"Text to hide/show 2"
<br style="font-size: medium; height: auto; line-height: normal;">
"Text to hide/show 3"
</div>
The Javascript code is as follows:
function processQuotes() {
$('.cls quote').each(function() {
var $quote = $(this);
var userId = $quote.parent().first().text(); /* For example */
/* See whether user is blocked */
if(blockUser[userId]) {
/* Hide text and br elements */
} else {
/* Show text and br elements */
}
});
}
I want to be able to hide the section from "Text to hide/show 1" to "Text to hide/show 3". I envisaged using the JQuery $var.Hide() and $var.Show() methods but I am struggling with how to get the parts I want to hide into $var.
Any help would be gratefully received.
Thanks,
Richard

I worte a sample, maybe could help:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.11.1.min.js" type="text/javascript" ></script>
</head>
<body>
<div class = "cls" id = "1234">
<quote>...</quote>
<p style="font-size: medium; height: auto; line-height: normal;">"Text to hide/show 1"</p>
<br />
<p style="font-size: medium; height: auto; line-height: normal;">"Text to hide/show 2"</p>
<br />
<p>"Text to hide/show 3"</p>
</div>
<script>
for(var i=0; i<3; i++){
(function(i){
$("#1234 p").eq(i).click(function(){
$("#1234 p").show();
$("#1234 p").eq(i).hide();
});
})(i);
}
</script>
</body>
</html>

Related

Making elements appear/disappear with Prototype

I need to make a make elements within a div appear and disappear when the div is clicked. When then webpage is loaded, it should just say "Click here". After clicking, new text saying "Click here again" should appear under the original text. After clicking again, new text appears under that saying "Click once more". After clicking again, all that text is deleted and new text saying "Thank you" appears. After clicking again, that text is deleted and new text saying "Goodbye" appears. After clicking once more, everything is deleted including the box that the text appears in. I am new to this and don't really know what I'm doing, and I can't even get an alert message to pop up when the div is clicked, which seems like it should be pretty simple. Here is my html code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="project4.css">
<script src="prototype.js" type="text/javascript"></script>
<script src="project4.js" type="text/javascript"></script>
</head>
<body>
<div id="main" class="box">
<p id="clickHere">Click here</p>
<p id="clickHereAgain">Click here again</p>
<p id="clickOnceMore">Click once more</p>
<p id="thankYou">Thank you</p>
<p id="goodbye">Goodbye</p>
</div>
</body>
</html>
My javascript code to just try to get an alert to pop up:
$(document).ready(function(){
$("div").click(function(){
alert("The paragraph was clicked.");
});
});
And my css code:
.box {
background-color: green;
color: white;
width: 300px;
height: 200px;
padding: 10px;
text-align: center;
font-size: 30px;
}
Here is a raw solution for your problem in jQuery, you may just transfer the logic to prototype.js:
$(document).ready(function() {
// turn off your paragraphs and buttons
$("#click2").hide();
$("#click3").hide();
$("#click4").hide();
$("#button2").hide();
$("#button3").hide();
$("#button4").hide();
// click the first button and hide and show the next
$("#button1").click(function() {
$("#click1").hide();
$("#button1").hide();
$("#button2").show();
$("#click2").show();
});
// click the second button and hide and show
$("#button2").click(function() {
$("#click2").hide();
$("#button2").hide();
$("#button3").show();
$("#click3").show();
});
// then the third
$("#button3").click(function() {
$("#click3").hide();
$("#button3").hide();
$("#click4").show();
});
});
And your HTML code:
<p id="click1">This is paragraph 1</p>
<button id="button1">Click me</button>
<p id="click2">This is paragraph 2</p>
<button id="button2">Click me again</button>
<p id="click3">This is paragraph 3</p>
<button id="button3">Click me one more time</button>
<p id="click4">You are done clicking</p>
Not an elegant solution, but those are the basics of it, jQuery has a toggle() function, just in case you need to give the user the ability to show the paragraph again. replace .show() and .hide() with .toggle()
For starters, set a click observer for the div and all of its children:
$("div").observe('click', myHandler);
Then perform the show/hide operation in myHandler.
A working example:
// array of paragraph ids to show/hide
const ids = ["clickHere", "clickHereAgain", "clickOnceMore",
"thankYou", "goodbye"];
const idCount = ids.length;
let index = 0;
// add click listener to div
$("main").observe('click', myHandler);
// handle the click
function myHandler () {
if (index >= idCount - 1) return;
// hide the currently visible paragraph
$(ids[index]).addClassName('hide');
// show the next paragraph
index++;
$(ids[index]).removeClassName('hide');
}
.hide {
display: none;
}
.box {
background-color: green;
color: white;
width: 300px;
height: 100px;
padding: 10px;
text-align: center;
font-size: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.min.js" type="text/javascript"></script>
<div id="main" class="box">
<p id="clickHere">Click here</p>
<p id="clickHereAgain" class="hide">Click here again</p>
<p id="clickOnceMore" class="hide">Click once more</p>
<p id="thankYou" class="hide">Thank you</p>
<p id="goodbye" class="hide">Goodbye</p>
</div>

JS DOM - Highlight texts with button unobtrusively

Basically, I have to create a button that when clicked, I need to retrieve all the paragraphs within the div and make their background highlighted.
Then I have to write the corresponding JS code (in an unobtrusive manner) to link the button to a function that highlights the paragraphs when clicked.
The button should act as a “toggle”, that is, if the paragraphs are already highlighted, then clicking the button unhighlight them. If the paragraphs aren’t highlighted, then clicking the button highlights them. The button’s text should change to reflect this so it should either say click to highlight or click to unhighlight. So far, I'm trying to create a function that iterates over these paragraphs but the highlight isn't working
** I know that the mark tag in html would highlight a text is there any way i can add that to my js code? **
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="task2.js"></script>
<style>
#poem {
padding: 10px;
margin-bottom: 10px;
color: blue;
font-size: 1.25em;
font-family: sans-serif;
background-color: silver;
border: 1px dashed black;
width: 30%;
}
</style>
</head>
<!- Modify code to add a button ->
<body>
<div id="poem">
<h2> How Many, How Much </h2>
<h4> by Shel Silverstein </h4>
<p> How many slams in an old screen door? </p>
<p> Depends how loud you shut it.</p>
<p> How many slices in a bread?</p>
<p> Depends how thin you cut it.</p>
<p> How much good inside a day? </p>
<p> Depends how good you live 'em. </p>
<p> How much love inside a friend? </p>
<p> Depends how much you give 'em. </p>
</div>
<button id="button"> Click to highlight </button>
</body>
</html>
js code:
function pageLoad() {
var button = document.getElementById("button");
button.onclick = okClick;
}
function okClick() {
var allParas = document.getElementsByTagName("p");
for (var i=0; i < allParas.length; i++) {
if(allParas[i].classList.contains('highlightClass')) {
allParas[i].classList.remove('highlightClass');
} else {
allParas[i].classList.add('highlightClass');
}
}
}
window.onload = pageLoad;
create a new class highlightClass.
if ( allParas[i].classList.contains('highlightClass') ) {
allParas[i].classList.remove('highlightClass');
}else{
allParas[i].classList.add('highlightClass');
}

UI problems - How do I trigger an image loading on choice made by dropdown box? Then add text to overlay the image result?

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.

Add text to a textarea with JavaScript

Again I got a problem with JavaScript, but this time is something more complex.
I'm trying to make a little JavaScript text editor. Basically it's an experiment, a test and the thing should be easy. I have a <h1> HTML element, and a <p> HTML element, and both of them change, as the user writes on a <input type="text" /> element and a <textarea></textarea>.
Now, everything work fine, but there is a problem. For making a space between lines, the user can't just press Enter, but of course need to use the <br /> HTML tag.
So my idea was to make a little button that allows the user to add this tag by pressing that button.
And JavaScript just makes a variable of the actual text, save it and add at the end of it the <br />. The result should be the text written by the user plus the break HTML tag.
And this works, if the textarea is empty and if you have never written something on it. It works and work even 10 or 20 times, but if you write something on it, it just stop working, even if you delete all the text. What is the problem in the code below?
<html>
<head>
<title>Text editor</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Slab" rel="stylesheet">
<style>
.title {
font-family: roboto;
text-align: center;
}
.text {
font-family: roboto slab;
text-align: justify;
margin-bottom: 40px;
}
.container {
width: 80%;
}
.textarea {
width: 100%;
height: 30em;
text-indent: 0.5em;
}
.title_box {
margin: 10px;
width: 20em;
padding: 10px;
font-size: 1em;
}
</style>
</head>
<body>
<center>
<div class="container">
<h1 class="title" id="title_space">Title of the page</h1>
<p class="text" id="text_space">Content of the page.</p>
</div>
</center>
<hr />
<center><input type="text" class="title_box" placeholder="Title" id="title_box" /></center>
<textarea class="textarea" id="text_box"></textarea>
<input type="submit" value="Save" onclick="saveText()" />
<input type="submit" value="br" onclick="br()" />
<script>
function saveText(){
var title = document.getElementById("title_box").value;
var text = document.getElementById("text_box").value;
document.getElementById("title_space").innerHTML = title;
document.getElementById("text_space").innerHTML = text;
}
function br(){
var actualtext = document.getElementById("text_box").value;
var processedtext = actualtext + "<br />";
document.getElementById("text_box").innerHTML = processedtext;
}
</script>
</body>
</html>
When you're updating the text area, instead of:
document.getElementById("text_box").innerHTML = processedtext;
Use:
document.getElementById("text_box").value = processedtext;
Try to add this to your JavaScript code just before changing the text
text = text.replace(/\r?\n/g, '<br>');
Line breaks are \r\n or \n while HTML line break is <br> and that is the problem.
This in case I understood your question correctly.
Here is the code running

.mouseover not working right in this code

just started learning Javascript and it's pretty hard. But I followed one tutorial and did as he told in his video, but still my result is not what I expected and what he got in his video. I wonder why is that and how I can fix that?
I want to get the box to appear out of nowhere with the text in it and follow the cursor for as long as it is inside the marked territory (LABEL- box in HTML).
Here's the code:
$("#rulesInfo").mouseover(function(e) {
var hovertext = "Info for the block will come here.";
$("#hoverdiv").text(hovertext).show();
$("#hoverdiv").css("top", e.clientY+10).css("left", e.clientX+10);
}).mouseout(function() {
$("#hoverdiv").hide();
});
#hoverdiv {
display: none;
position: absolute;
font-size: 12px;
background-color: #161616;
color: #fff;
border: 1px solid red;
padding: 8px;
border-radius: 5px;
}
<FORM>
<DIV ID="bottom">
<P>
<INPUT TYPE="checkbox" NAME="checkedRules" VALUE="yes" REQUIRED /><LABEL FOR="checkedRules" ID="rulesInfo">I have read the Rules and Conditions for the trip.</LABEL>
</P>
</DIV>
</FORM>
<DIV ID="hoverdiv"></DIV>
<SCRIPT TYPE="text/javascript" SRC="jquery.js"></SCRIPT>
<SCRIPT TYPE="text/javascript" SRC="app.js"></SCRIPT>
What you would like to do is user the mousemove event which fires on every mouse move of the object. mouseover only occurs when the mouse first moves over the object.
see here:
$("#rulesInfo").mousemove(function(e) {
var hovertext = "Info for the block will come here.";
$("#hoverdiv").text(hovertext).show();
$("#hoverdiv").css("top", e.clientY+10).css("left", e.clientX+10);
}).mouseout(function() {
$("#hoverdiv").hide();
});
http://jsfiddle.net/mzwj26a7/

Categories