I'm using a search function to highlight text (function 2) in different chapters. In parallel most of this text is stored in div called content to ease reading. You can toggle these div to read the text (function 1).
When text is found by function 2, it's no longer possible to toggle the text in this chapter. I suppose this is related to use of "this" in function 1 (If I delete this it works) or handlers (if I add live in front of click in function 1 it works but live is deprecated and remplacement "on" is not working).
// function 1 : toggle content when clicking the button
$(".chapter button").on('click',function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
console.log(id)
$('#' + id + '+*').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
console.log(str);
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
// but i want to highlight all occurences of the word in this chapter ? how can I define index d ?
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
$(this).html($(this).html().replace(strCut[i], '<font color="red">$&</font>'));
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
The problem was your $(this).html(). The .replace that you did removes the event listener of your button, because it modifies the DOM. Instead of getting the whole .html(), I did it with .children(), and then replaced just the text of it.
About replacing all the occurrences of the chapter word, you could use a Regular Expression. Using a string will replace just the first occurrence of the string. With the regular expression you can replace all of them.
// function 1 : toggle content when clicking the button
$(".chapter button").click(function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
$('#' + id + '+*').closest('.content').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
var regex = new RegExp(strCut[i],"g")
$(this).children().each(function (index,element) {
const text = $(element).html().replace(regex,'<font color="red">$&</font>')
$(element).html(text)
})
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1 and the second ocurrence of chapter also highlighted
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
EDIT
I wasn't clear enough about the errors, sorry, and I've noticed the right solution.
The point is that, instead of modifying the parent element, I've changed the text of the childrens. When you change the whole html, you remove the listener of your buttons when you add it again to the html, and that's why isn't possible to toggle the divs.
Related
I got a problem with one of the sites with JavaScript, and I need to automate a click and then find out how many turns I got before I run out of them. As in, for example, let's say I have 8 turns. So what I would need is to automatically have JavaScript to trigger said div id, 8 times. (As in, I add like this)
Link:https://jsfiddle.net/yxsgp8tc/
<body>
<button id="test">Test</button>
<p>
On box should be number of tests
</p>
<form>
<label><input type="text"/>00-99</label>
<button>
trigger it
</button>
</form>
</body>
in plain javascript, you would target unique elements (using an id) by using document.getElementById('<element_id'). If you wanted to target a class, you would document.querySelector('.<class_name>') for the first instance of the class, or document.querySeletorAll('.<class_name>')
Also, your input tag was misspelled "imput", and is a singleton tag so you don't have to close it off.
Assuming you wanted a way to trigger a click event, here's a basic example:
<head>
<script>
const test = document.getElementById('test');
const trigger = document.getElementById('trigger')''
test.addEventListener('click', () => {
const num_test = document.getElementById('num_tests').value;
for (let i = 0; i < num_test; i++) {
trigger.click();
}
});
trigger.addEventListener('click', () => {
console.log('trigger clicked');
});
</script>
</head>
<body>
<button id="test">Test</button>
<p>
On box should be number of tests
</p>
<form>
<input type="text" id="num_tests" value="">
<button id="trigger">
trigger it
</button>
</form>
</body>
https://jsfiddle.net/qr1z3d6e/2/
first in the jsfiddle.net link there are some errors such as imput instead of input.
I haven't tested it, but if I understand correctly is it something like this? try it.
<body>
<input id="myinput" type="text">00-99</input>
<button id="clickme">
</body>
<script>
var button = document.getElementById("clickme"),
count = 99;
var myInput = document.getElementById("myinput")
button.onclick = function(count){
count -= 1;
myInput.innerHTML = "00 " + count;
};
</script>
I have written code that creates a checkbox list where when i click the checkbox below my list of options i would like a link to show underneath that the user can click (show/hide) I cannot figure out why my code will not work. If the user unchecked the box the link disappears but nothing happens when i click my check boxes. I would like to do this fix in JQuery
<!DOCTYPE html>
<html>
<div class ="container">
<head></head>
<body>
<input id="grp1" type="checkbox" value="group_1" onClick="http://google.com" />
<label for="grp1"> group 1 </label>
<div>
<input id="grp2" type="checkbox" value="group_2" onClick="http://google.com" >
group_2</label>
</div>
</body>
</html>
You'll have to use javascript to hide/show the wanted elements in html. There are many approaches to this. The most basic one would be something like
<!DOCTYPE html>
<html>
<body>
<div id="container">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("container").onclick = function (e) {
//check every box if it's checked
if (document.getElementById('grp1').checked) {
document.getElementById('url1').style.display = 'block';
} else {
document.getElementById('url1').style.display = 'none';
}
if (document.getElementById('grp2').checked) {
document.getElementById('url2').style.display = 'block';
} else {
document.getElementById('url2').style.display = 'none';
}
}
</script>
</body>
</html>
Of course you can use different approaches like creating the element in javascript then adding it to the html if you don't like the idea if existing hidden elements. You might also use loops to loop through checkbox element and simply show/hide the url accordingly. And more to make the code flexible on any number of boxes. Something like this
<!DOCTYPE html>
<html>
<body>
<div id="container">
<div id="checkBoxContainer">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
</div>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("checkBoxContainer").onclick = function (e) {
var linkNumber = 1; //This is number of the first url element with ud url1
var containerChildren = document.getElementById("checkBoxContainer").children;
//loop through the children elements
for (var i = 0; i < containerChildren.length; i++) {
var oneChild = containerChildren[i]; //catch only one child in a variable
//simply filter the input elements which are of type checkbox
if(oneChild.tagName === "INPUT" && oneChild.type === "checkbox"){
//Show or hide the url accordingly.
if (oneChild.checked) {
document.getElementById('url' + linkNumber++).style.display = 'block';
} else {
document.getElementById('url' + linkNumber++).style.display = 'none';
}
}
}
}
</script>
</body>
</html>
The onclick HTML attribute doesn't work that way. The attribute value is executed as javascript. You can make a js function to show/hide the link.
Hi you want to try this:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.group-link{
display: block;
}
.hidden{
display: none;
}
</style>
</head>
<body>
<div class="jsParent">
<label for="grp1">
<input id="grp1" type="checkbox" value="group_1" onchange="showLink(this)"/> group 1
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/dogs-101/videos/the-doberman">Group 1 Link</a>
</div>
<div class="jsParent">
<label for="grp2">
<input id="grp2" type="checkbox" value="group_2" onchange="showLink(this)"/> group_2
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/cats-101/videos/ragdoll">Group 2Link </a>
</div>
<script type="text/javascript">
function showLink(el){
var parent = el.parentElement.parentElement;
var linkEl = getAnchorEl(parent);
if(linkEl){
if(el.checked){
linkEl.classList = linkEl.classList.value.replace('hidden', '');
}else{
linkEl.classList = linkEl.classList.value + ' hidden';
}
}
}
function getAnchorEl(parent){
var childrens = parent.children;
var linkEl = null;
for (var i = 0; i < childrens.length; i++) {
var childEl = childrens[i];
if(childEl.classList.value.indexOf('jsLink') > -1){
linkEl = childEl;
break;
}
}
return linkEl;
}
</script>
</body>
</html>
Your question is undoubtedly a duplicate but I am answering because I would like to help you identify issues with the code you posted.
I notice you have a <div>tag between your tag and tag. Why? This is a bit of an over simplification but as a general rule never put anything between your <html> and <head> tag and only place <div> tags inside your <body> tag. Also be mindful of how you nest your elements. That tag starts after and before .
Even if that were correct placement you close the before you close your div arbitrarily in the middle of your body tag. you should never have
<div>
<p>
</div>
</p>
Instead it should look like this
<div>
<p>
</p>
</div>
In your onClick attribute you have a random URL. That will not open a new window. You new too put some javascript in there.
<input onClick="window.open('http://google.com')">
Also your second label tag does not have an opening, just a </label> close tag
To answer your question - I suggest you look at the jQuery toggle function.
<input type="checkbox" id="displayLink" />
Google
<script type="text/javascript">
$("#displayLink").click(function(){
$("#googleLink").toggle();
});
</script>
As a general rule you should favor event handlers (such as the $("").click() posted above) to handle events (like clicking) as opposed to html attributes such as onClick.
I want to make a button (out of divs) and a paragraph (or any text field) below the divs that counts the clicks.
$(document).ready(function() {
$('#butt').mousedown(function() {
$("#butt").hide();
});
$("#pushed").mouseup(function() {
$("#butt").show();
});
$("#butt").click(function() {
button_click();
});
});
var clicks = 0;
function button_click() {
clicks = parseInt(clicks) + parseInt(1);
var divData = document.getElementById("showCount");
divData.innerHTML = "Clicks:" + clicks;
}
<!-- <link type="text/css" rel="stylesheet" href="CSS.css"/> -->
<form name="ButtonForm">
<div id="container">
<div id="pushed"></div>
<div id="butt"></div>
</div>
<div id="showCount"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<!--<script src="Untitled-1.js" type="text/javascript"></script>-->
</form>
Your div elements are empty and there is no CSS to give them any explicit size, so they will never be visible for you to click on them.
Also, the mousedown event handler can and should be combined with the click handler for butt and the mouseup event handler should just be a click event as well.
Additionally, you only need to update the number of clicks, not the word "Clicks", so make a separate placeholder for the number with a span element and then you can hard-code the word "Clicks" into the div.
Lastly, to increment a number by one, you can just use the pre or post-increment operator (++).
$(document).ready(function() {
var clicks = 0;
var divData = $("#clickCount");
$("#pushed").on("click", function() {
$("#butt").show();
});
$("#butt").on("click", function() {
$("#butt").hide();
clicks++; // increment the counter by one
divData.html(clicks);
});
});
#pushed, #butt {height:50px; width:150px; background-color:green; margin:5px;}
<body>
<form name="ButtonForm">
<div id="container">
<div id="pushed"></div>
<div id="butt"></div>
</div>
<div id="showCount">Clicks <span id="clickCount"></span></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
</form>
</body>
First of all, you should simplify your code. Hiding and showing the button is not necessary to produce the result you are looking for.
Second, change the #butt element to an actual button so that you have something to see and click.
Third, make sure your script is loading after jquery is included.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<button id="butt">I'm a button</button>
<div id="showCount"></div>
<script>
$(document).ready(function() {
$("#butt").click(function() {
button_click();
});
var clicks = 0;
function button_click() {
clicks = parseInt(clicks) + parseInt(1);
var divData = document.getElementById("showCount");
divData.innerHTML = "Clicks:" + clicks;
}
});
</script>
This question already has answers here:
Find a string of text in an element and wrap some span tags round it
(6 answers)
Closed 6 years ago.
I've got a loot box div in which (sometimes) the name colorful comes in.
for example:
<div id="columns">
<div id="loot">
<b>
"Loot: Colorful blade "
<br>
" slot: weapon "
<br>
" value: 7"
</b>
...more and more and more
Now if the text in the loot div contains colorful I want to add a class to the text colorful . So I thought that if the text colorful is in it, it puts a <span> around the word colorful and asign a class to it. But I cant figure out how to do this.
I tried this (jsfiddle)
Your code targets the #loot element when trying to add the rainbow class, but does it target the desired div when looking for the text in the first place? (I dont think it does, but dunno since I dont jQuery)
Here's some code to do it sans jQuery:
var tgtElem = document.getElementById('loot');
var value = tgtElem.innerHTML;
value = value.replace('Colorful', '<span class="highlight">Colorful</span>');
tgtElem.innerHTML = value;
It relies upon a css rule, .highlight - set its styles as you wish.
Here's a fully worked example:
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id){return document.getElementById(id);}
//////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
var tgtElem = byId('loot');
var value = tgtElem.innerHTML;
value = value.replace('Colorful', '<span class="highlight">Colorful</span>');
tgtElem.innerHTML = value;
}
</script>
<style>
.highlight
{
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<div id="columns">
<div id="loot">
<b>
Loot: Colorful blade
<br>
slot: weapon
<br>
value: 7
</b>
<br />
<br />
<b>Current slot: weapon <br> Current weapon : Colorful blade <br> Current value: 7</b>
</div>
</div>
</body>
</html>
You need to link to the libary for the jQuery to work.
You can get it here https://code.jquery.com/
You were also correct with using the span around the word. Here is a working version
Loot: <span>Colorful</span> blade
Then target it to add the class
if ($('#loot:contains("Colorful")').length > 0) {
var str = document.getElementById("loot").innerHTML;
var res = str.replace("Colorful", "<span>Colorful</span>");
document.getElementById("loot").innerHTML = res;
$("#loot span").addClass("rainbow");
}
https://jsfiddle.net/o7phybe8/6/
my page is full of php-generated content split in div's that have the same class but no id's. I want to show some buttons that allow me to manage, change and delete the div's; the buttons should be able to change the class, delete the div and select the content of the div.
How can I do this? is there a way to set the button's onclick action to something, say ... onclick="changetheclass(this)" that would actually change the class of the div containing this button?
Man I feel I'm not making any sense here :(
Did anyone understand what I'm talking about? If so, is there any possibility to do this?
Thanks in advance!
:)
EDIT: this is one of the divs, so that you could understand what I'm talking about:
<div class="box"><p>
this is the content of the div
<button onclick="change_the_class(this_div_or_something)">click here to change the class of the div</a>
<button onclick="select_the_content(this_div_or_something)">click here to change the class of the div</a>
<button onclick="delete_the_whole_div(this_div_or_something)">click here to change the class of the div</a>
</p></div>
Is this what you looking for ??
<html>
<head>
<script type="text/javascript">
function changeClass(elm) {
elm.parentNode.className ='newcss';
}
function deleteDiv(elm) {
var par = elm.parentNode;
var gran = par.parentNode;
gran.removeChild(par);
}
</script>
</head>
<body>
<div class='test'>
Hello
<button onclick="javascript:changeClass(this);" value="Change CSS">CSS</button>
<button onclick="javascript:deleteDiv(this);" value="Change CSS">Delete</button>
</div>
<div class='test'>
Hello
<button onclick="javascript:changeClass(this);" value="Change CSS">CSS</button>
<button onclick="javascript:deleteDiv(this);" value="Change CSS">Delete</button>
</div>
<div class='test'>
Hello
<button onclick="javascript:changeClass(this);" value="Change CSS">CSS</button>
<button onclick="javascript:deleteDiv(this);" value="Change CSS">Delete</button>
</div>
<div class='test'>
Hello
<button onclick="javascript:changeClass(this);" value="Change CSS">CSS</button>
<button onclick="javascript:deleteDiv(this);" value="Change CSS">Delete</button>
</div>
</body>
</html>
in JS, you can use querySelectorAll:
//get all divs with class "myDiv"
var divs = document.querySelectorAll('div.myDiv');
//for each of the gathered divs, do something with it
for(var i=0; i< divs.length;i++){
var aDiv = divs[i];
//"aDiv" is a div in the collection of matched divs
//you can do anything with it: add buttons etc.
}
First stay away from onclick="something" - inline JavaScript. then yes you can still manage to do what you want to do without ids.
var divs = document.getElementsByTagName('div'),
result = [],
len = divs.length,
i = 0,
aLink;
for(; i < len; i++){
// update the condition if there can be more than one class name as this assume a single class name
if (divs[i].className == 'myClassName') result.push(divs[i]);
}
len = result.length;
i = 0;
for (; i < len; i++) {
aLink = document.createElement('a');
aLink.innerHTML = 'Edit';
aLink._parent = result[i]; // store a reference to the parent div
aLink.href = '#';
aLink.onclick = function(ev) {
ev.preventDefault();
// do your edit stuff here, ev.target._parent contain the targetted div
};
result[i].appendChild(aLink);
}
$('div.my-class').each( function( index, element ){
var div = $( element ); // not sure if this is needed
// add the buttons, e.g. via div.html('');
// add the buttons' click handlers
});