I have a textarea that contains several images. All images have an id and I want to loop through all of those images and check if the need an onclick event (depends on id)
If the do not need a onclick event I need to check if the have one and remove it. If the need I I still need to remove it and add another (because the value of the onclick could be changed)
How can I do this?
<img id="slideShowImage_3" style="border: 1px solid black; cursor: pointer;" title="3" onclick="loadSlideShow('7','open','3','','2')" src="uploads/nieuws/7/1363788115.jpg" alt="3" />
<img id="slideShowImage_3" style="border: 1px solid black; cursor: pointer;" title="3" src="uploads/nieuws/7/1363788115.jpg" alt="3" />
http://jsfiddle.net/wmrqk/4/
Try this:
function cleanCode() {
var container = $('<div>' + $('#text1').val() + '</div>');
container.find('img').removeAttr('onclick');
$('#text2').html(container.html());
}
Demo
May not be cool, but you can do something like
function cleanCode() {
var els = $($('#text1').val());
els.each(function(i, v){
var $this = $(this);
if($this.attr('id') == 'slideShowImage_1'){
$this.removeAttr('onclick')
}
});
console.log($('<div></div>').append(els).html())
}
Demo: Fiddle
For a very simple HTML like the one you have here you could do this :
$('#text2').html($('#text1').html().replace(/onclick="[^"]*"/g,''));
But be very careful : parsing HTML in regex fails in general cases so you can only do that if you know where your HTML comes from and what it is like.
If your HTML is well formed, you can also do this :
var e = $('<div>'+$('#text1').val()+'</div>');
e.find('img').attr('onclick','');
$('#text2').html(e.html());
Demonstration
In any case, be aware that this couldn't be used as a security measure.
Related
I have an input field where I would like to have the characters turn red after the 10th symbol.
So far I have:
var street_1 = document.getElementById('street_1');
street_1.style.color = "red";
Which changes the color of all the characters. Then I tried using:
street_1.value.substring(10,100).style.color = "red";
which of course didn't work since .style as I learned only works for the entire field and not just the value.
Since im completely new to JS I really have no idea how to approach this.
You can hide the input field, and add another span element that displays its value as follows:
HTML:
<div>
<input type="text">
<span class="text"></span>
</div>
CSS:
input {
opacity: 0;
width: 100%;
}
div {
position: relative;
border: 1px solid #000;
}
.text {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.red {
color: red;
}
JS:
var span = document.querySelector('span');
var input = document.querySelector('input');
input.addEventListener('keydown', function(evt) {
var value = evt.target.value;
span.innerHTML = value.substring(0, 10) + '<span class="red">' + value.substring(10) + '</span>'
});
You can find a working fiddle here https://jsfiddle.net/v127c14p/
in html you can't define sub elements in the value of input fields because it is allways a simple string and not a html element. so you only can define the color for the input element and the complete text.
<input type="text" value="my <em style='color: red;'>test</em>"> is not possible
<input type="text" value="my test" style="color: red;"> is the only way to mark the text
what can be a sollution, define a simple div tag, write the value of your input filed inside that, and mark the text in that div tag by surrounding with a span tag and setting a class to this
Edit:
best practice is, simply show a red border on the input field and tell the user with a popup what exactly is wrong with his input (bootstrap modals or jquery-confirm.js for excample)
Note: If I explicitly need an <input> field and not just user-editable text, this solution won't work!
It is a quite old question, but maybe someone finds this solution helpful.
It uses the contenteditable tag, to allow the user to type / change text in an normal HTML element and JS to check and color the text.
The field check can, for example, also be done with "onkeyup" for immediate feedback to the user, but this will also reset the text cursor to the beginning of the field.
HTML:
<a id="sample_id" onblur="color_overlength_func('sample_id', 20)" contenteditable="true">Some Text</a>
JS:
function color_overlength_func(textfield_id, max_length) {
let text_temp = document.getElementById(textfield_id).innerHTML;
if (text_temp.length >= max_length) {
let text_OK = text_temp.substr(0, max_length);
let text_to_long = text_temp.substr(max_length);
document.getElementById(textfield_id).innerHTML = "" + text_OK + "<em style='color:red;'>" + text_to_long + "</em>";
}
}
You can find a working fiddle here: https://jsfiddle.net/kyh9803c/
You can do a substring and append a element like span and then target the span with css or js directly.
You can use CSS. Although javascript library need to load everytime
you mean something like this
<div>
HELL<span class="red" style="color:red">O</span>
</div>
I try to paste text into multiple fields, but the formatting is only cleared on the first element, not the second etc.
I found this question https://stackoverflow.com/a/12028136/3955607 which works fine, but again, on multiple elements it doesnt work.
So I got this HTML
<div style="color:red">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>
and this javascript:
document.querySelector("div[contenteditable]").addEventListener("paste", function(e) {
e.preventDefault();
var text = e.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
I have this fiddle http://jsfiddle.net/tdjuc8es/
just copy and paste the Some rich HTML- text and see what happens
Someone who can help me out?
document.querySelector yields one element. You want to use document.querySelectorAll to get all matching elements, and then iterate over that collection.
var editors = document.querySelectorAll('div[contenteditable]');
for(var i = 0, l = editors.length; i < l; i++) {
editors[i].addEventListener('paste', myCustomPasteFunction);
}
Fiddle
If you're used to jQuery, you might think that document.querySelector() fulfils the same kind of function; however, it only returns the first element that matches the selector; instead you should have used document.querySelectorAll() and then used iteration to add your event handlers.
Since you've tagged it as jquery, you could also consider this:
$("div[contenteditable]").on("paste", function(e) {
e.preventDefault();
var text = e.originalEvent.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
div[contenteditable] {
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="color:blue">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>
I'm using e.originalEvent here because the one that jQuery passes you in the event handler is a wrapper object.
It is beacause the document.querySelector only return the first matched element.
You can use document.querySelectorAll instated.
Wish it can help you.
How can I have elements .show in the order they're clicked and not the order they're appear in the HTML using jquery?
E.g.
Css code:
.sq{
display:none;
}
Html Code:
A
B
C
<span class="sq" id="01">a</span>
<span class="sq" id="02">b</span>
<span class="sq" id="03">c</span>
JavaScript code:
$("#1").click(function(){
$("#01").show();
});
$("#2").click(function(){
$("#02").show();
});
$("#3").click(function(){
$("#03").show();
});
Using this code if I click C,B,A the output will arrange "a b c"
What I would like is if I click C,B,A the output should arrange "c b a"
I've tried various CSS positioning rules to do this, but the best I can do is have them arrange in the same position as each other. I realize I could make a new class for each but would rather not do it that way in the interest of minimal code and I'm learning right now so it would be useful to know a better way around the issue.
Here's a fiddle: http://jsfiddle.net/xuxsuagg/4/
You can do something like
$(".myclass").one('click', function() {
$($(this).data('target')).appendTo('.output').show();
});
a {
text-decoration: none;
}
.sq {
display: none;
}
.output {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
A
B
C
D
E
F
<p class="output">
<span class="sq" id="01">A</span>
<span class="sq" id="02">B</span>
<span class="sq" id="03">C</span>
<span class="sq" id="04">D</span>
<span class="sq" id="05">E</span>
<span class="sq" id="06">F</span>
</p>
Notes
Used a common event handler instead of using different handlers for each link
Before shown the element the target is moved to the last position of the parent
Used .one() to register the handler so that one element is shown only once
There is a very simple trick: use .append(). When you append a selected element that is already present in the DOM, you are actually moving it around. Also, I recommend that to optimize your code, you can:
Use a common class for the <a> elements
Assigned a HTML5 data- attribute, say data-target, to specify the ID of its intended target
Listen to click events triggered on the common class
An example of the proposed new markup:
A
B
<!-- and more -->
Here is the code (and the demo fiddle here—http://jsfiddle.net/teddyrised/xuxsuagg/9/)
$('.sq-click').click(function(e) {
// Prevent default action
e.preventDefault();
// Use .append() to move element
var $out = $('.output');
$out.find('#'+$(this).attr('data-target')).appendTo($out).show();
});
On a side note, if you do not want the users to rearrange the order after an anchor has been clicked, you will have to rely on the .one() method for listening to click events. Also, it will help that you style the disabled anchors appropriately so the users can see it—see proof-of-concept demo: http://jsfiddle.net/teddyrised/xuxsuagg/26/
$('.sq-click').one('click', function(e) {
// Prevent default action
e.preventDefault();
// Use .append() to move element
var $out = $('.output');
$out.find('#'+$(this).attr('data-target')).appendTo($out).show();
// Add class to change appearance of disabled <a>
$(this).addClass('disabled');
});
And your CSS can look like this:
.disabled {
cursor: default;
opacity: 0.2;
}
You can simplify this code to:
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
a {
text-decoration: none;
}
.sq {
display: none;
}
A
B
C
D
E
F
<p class="output">
</p>
Bind the click event to the class that they share and not their own unique id.
In the function scope of clickClosure 'this' is referring to the current element.
$(".sq").click(function clickClosure(){
$(this).show();
});
Using styles to achieve this might range from painful to very hard, depending on the exact way you want them displayed. I'd suggest instead to re-order them in DOM. That might look something like this:
<a id="link-1">...</a>
...
<div style="display: none" id="hidden-items">
<span id="item-1">...</span>
</div>
<div id="visible-items"></div>
&
$('#link-1').click(function () {
$('#visible-items').append($('#item-1'));
});
As other respondents suggested, you could also optimize your code in various ways, but that's outside the scope of the question.
Try this: You can put empty <p class="output"> and remove display:none; from CSS .sq{... In jQuery, create a <span> on the basis of clicked link and append it to <p class="output">
HTML:
A
B
C
D
E
F
<p class="output">
</p>
CSS:
.sq{
/*display:none;*/
color: green;
margin-right: 10px;
}
jQuery
$("a[href='#']").click(function(e){
e.preventDefault();
var text = '<span class="sq" id="0'+$(this).prop('id')+'">'
+$(this).text()+'</span>';
$(text).appendTo('p.output');
});
DEMO
Can any one tell me, how i can select and alert text "__user_Name_" which is immediate to img with. i am using j query selector.
<div id="side-bar" class="test" style="">
<ul>
<li alt="User options">
<a href="#" name="nav1">
<img alt="USERNAME" src="myprofile.png" style="vertical-align: bottom; border: 0px solid rgb(255, 255, 255);">__user_Name_
</a>
</li>
You can't use a selector, but you can access it vai
var el = $('img').prop('nextSibling')
here el will be a dom element reference, not a jQuery object.
If you just want to read the text then you can use
var text = $('img').text()
I think what you're wanting is the following, though I'm not sure if I've read your question correctly:
To get the text: $('a[name="nav1"]').text()
To set the text: $('a[name="nav1"]').text("New Text")
You could use the .text() method with on the 'a' selector. Something like:
var selected = $('a').text();
alert(selected);
jsFiddle
I would like to achieve the same effect found on the following website:
http://www.kpf.com/projectlist.asp?T=4
On mouseover of an image, the corresponding text highlights and vice versa.
I've found a JavaScript solution on a forum. I've copy-pasted the solution below:
div code
<div style="width:400;height:500;" onmouseover="hightlight()" onmouseout="removehightlight()"><span id="textspan" >This is a test div to show mouseover</span><img id="imgsrc" src="/images/test.gif" /></div>
javascript
<script language="javascript">
function hightlight()
{
document.getElementById("textspan").style.color = "blue";
document.getElementById("imgsrc").style.border = "1px solid blue";
//document.getElementById("textspan").setStyle("color","blue");
//document.getElementById("imgsrc").setStyle("border","1px solid blue");
}
function removehightlight()
{
document.getElementById("textspan").style.color = "black";
document.getElementById("imgsrc").style.border = "0px solid blue";
}
</script>
However, this solution is for an image and text in the same div. My image and text reside in two separate divs like so:
javascript
function hightlight()
{
document.getElementById("textspan").style.text = "underline";
document.getElementById("imgsrc").style.border = "5px solid #005596";
}
function removehightlight()
{
document.getElementById("textspan").style.text = "none";
document.getElementById("imgsrc").style.border = "5px solid white";
}
text
<div id="left-menu" >
<div align="right">
<p><!-- #BeginLibraryItem "/Library/left-projects-category.lbi" --> <span class="left-title">Category</span><!-- #EndLibraryItem --><br />
<span class="left-sub">Residential</span><br />
<span id="textspan" onmouseover="hightlight()" onmouseout="removehightlight()">11 Gurney Drive</span><br />
<span id="textspan" onmouseover="hightlight()" onmouseout="removehightlight()">78 LAD</span><br />
</p>
</div>
</div>
image
<div style="float:left; margin:90px 0 0 305px; padding:0 0 100px 0; height:auto;">
<img src="../../images/completed-projects/thumbnails/11-gurney-drive.jpg" width="215" height="170" id="imgsrc" style="border:5px solid white" onmouseover="hightlight()" onmouseout="removehightlight()"/>
<img src="../../images/completed-projects/thumbnails/78-lad.jpg" width="215" height="171" id="imgsrc" style="border:5px solid white" onmouseover="hightlight()" onmouseout="removehightlight()"/>
/div>
MY PROBLEMS
Let's call 11 Gurney Drive - Text1 and 11-gurney-drive.jpg - Image1
78 LAD - Text2 and 78-lad.jpeg - Image2.
My problems:
On Text1 mouseover, it highlights both Text1 and Image1 - Good.
On Text2 mouseover, it highlights Text2 and Image1 - it should highlight Text2 and Image2.
On Image1 mouseover, it highlights only Image1 - it should highlight Text1 and Image1.
On Image2 mouseover, it highlights only Image1 - it should highlight Text2 and Image2.
I have very little experience in customising Javascript; have tried Googling getElementbyId but it all might as well be in Greek.
Edit
I forgot to mention that I've tried adding a 2nd unique element ID called textspan2 and imgsrc2 but that didn't seem to work. What I did:
javascript
function hightlight()
{
document.getElementById("textspan").style.text = "underline";
document.getElementById("imgsrc").style.border = "5px solid #005596";
document.getElementById("textspan2").style.text = "underline";
document.getElementById("imgsrc2").style.border = "5px solid #005596";
}
function removehightlight()
{
document.getElementById("textspan").style.text = "none";
document.getElementById("imgsrc").style.border = "5px solid white";
document.getElementById("textspan2").style.text = "none";
document.getElementById("imgsrc2").style.border = "5px solid white";
}
text
<div id="left-menu" >
<div align="right">
<p><!-- #BeginLibraryItem "/Library/left-projects-category.lbi" --> <span class="left-title">Category</span><!-- #EndLibraryItem --><br />
<span class="left-sub">Residential</span><br />
<span id="textspan" onmouseover="hightlight()" onmouseout="removehightlight()">11 Gurney Drive</span><br />
<span id="textspan2" onmouseover="hightlight()" onmouseout="removehightlight()">78 LAD</span><br />
</p>
</div>
</div>
image
<div style="float:left; margin:90px 0 0 305px; padding:0 0 100px 0; height:auto;">
<img src="../../images/completed-projects/thumbnails/11-gurney-drive.jpg" width="215" height="170" id="imgsrc" style="border:5px solid white" onmouseover="hightlight()" onmouseout="removehightlight()"/>
<img src="../../images/completed-projects/thumbnails/78-lad.jpg" width="215" height="171" id="imgsrc2" style="border:5px solid white" onmouseover="hightlight()" onmouseout="removehightlight()"/>
/div>
getElementById is one of those calls that actually does what it says. :-) It gets a DOM element by its id attribute. Since id must be unique, it gets you one specific element that you can then interact with (for instance, setting its style properties).
So part of your problem is that you have two elements with the ID "textspan", and two elements with the ID "imgsrc", which means the browser will do something undefined because you can't do that.
Within an event handler, this will point to the element that you've put the handler on. So in your highlight and removeHighlight functions, you can use this (rather than getElementById) to get a reference to the img DOM elements. That just leaves the text ones.
You could use a naming convention ("textspan1" and "imgsrc1", "textspan2" and "imgsrc2" for instance), so the handlers would look like this:
function hightlight()
{
var textid = this.id.replace("imgsrc", "textspan");
var text = document.getElementById(textid);
text.style.color = "blue";
this.style.border = "1px solid blue";
}
function removehightlight()
{
var textid = this.id.replace("imgsrc", "textspan");
var text = document.getElementById(textid);
text.style.color = "black";
this.style.border = "0px solid blue";
}
...or you might use an attribute (say, data-text) on the img tags that gives the ID of the text field linked to it; you can get an attribute from a DOM element like this:
var textid = this.getAttribute("data-text");
Custom attributes are invalid in HTML4 and below, but I've never met a browser that had a problem with them. In HTML5 and above, you can have custom attributes as long as they start with data- as above. So if validation is part of your working practices (and it's usually a good idea), you might consider starting to use the HTML5 doctype unless you have a particular reason for staying with the previous one (like, for instance, you're uncomfortable using a doctype for a version of HTML5 that hasn't even reached candidate recommendation stage yet). A lot of us are happy enough to go ahead now.
this is not the element the way you're hooking up the handlers. I'd forgotten, it's been a long time since I used the DOM0 way of hooking up handlers (onmouseover=). But the below works:
Or, because of the way you're attaching the handlers, you could pass an argument into the functions telling them which one they're dealing with:
function hightlight(index)
{
var img = document.getElementById("imgsrc" + index);
var text = document.getElementById("textspan" + index);
text.style.color = "blue";
img.style.border = "1px solid blue";
}
function removehightlight(index)
{
var img = document.getElementById("imgsrc" + index);
var text = document.getElementById("textspan" + index);
text.style.color = "black";
img.style.border = "0px solid blue";
}
...where your onmouseover and onmouseout attributes changes to:
onmouseover="hightlight(1);" onmouseout="removehightlight(1);"
onmouseover="hightlight(2);" onmouseout="removehightlight(2);"
Here's a live example.
Side note: The code you've found is using the mouseover and mouseout events. Be aware that those don't quite do what you may expect they do, and it can bite you, although the specific way you're using them is mostly fine (you're doing more work than necessary, but that's okay). But suppose your markup changed a little:
<span id="textspan" onmouseover="hightlight()" onmouseout="removehightlight()">11 <strong>Gurney</strong> Drive</span><br />
Now there's an element within the span that you're watching those events on. That means that as the user's mouse travels from left-to-right, you'll see a series of mouseover events as the mouse travels over the text "11(space)", then your code will see a mouseout event as the mouse moves over into the word "Gurney". Why does this happen? Because the mouse has moved out of the span and into the strong element. Then it will immediately see another mouseover, because the mouse is moving over the strong element and the mouseover event bubbles up the DOM, so we see it on the span. This may cause flicker as the mouse moves into and out of the strong element.
Internet Explorer has the mouseenter and mouseleave events, which are more suited to what you're doing — but who wants to use events that are limited to only one brand of browser? Well, most good JavaScript libraries emulate these events even on browsers that don't support them natively, which brings me to...
Off-topic 1:
If you're just starting out with JavaScript on browsers, a word of warning: There are a number of browser inconsistencies and awkwardnesses (if that's a word) that libraries like jQuery, Prototype, YUI, Closure, or any of several others can smooth over for you. For what you're doing in this question, enh, they wouldn't bring a huge amount of value. But for more complicated stuff, they can save you a lot of time and trouble, leveraging the good work many others have done before you. Like, for instance, emulating mouseenter and mouseleave on browsers that don't support them. :-) I know for a fact both jQuery and Prototype do that for you, and I suspect others do as well.
Off-topic 2:
It's "highlight", not "hightlight". If someone needs to come maintain your code later, that typo (which is consistent, and so not a bug!) might well trip them up. Separately, the standard practice (which you're free to ignore!) is to camelCase words in function names, so removeHighlight rather than removehightlight. FWIW.