I have a label which displays an IP address:
<label id="internet_ipaddr" class="label_s1"></label>
What I want to do is display a div, #youareoffline if the label is empty. This was suggested as an implementation but after playing around I can't get it to work:
if (string.IsNullOrWhiteSpace(#internet_ipaddr)) {
$(#youareoffline).show();
}
The code you've attempted to use looks like a mix of C# (string.isNullOrWhiteSpace()) and pseudo code, not valid JS.
To make this work you can check if the element has any children (text nodes or otherwise) using the is(':empty') method, then show the relevant element. Try this:
if ($('#internet_ipaddr').is(':empty')) {
$('#youareoffline').show();
}
#youareoffline { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="internet_ipaddr" class="label_s1"></label>
<div id="youareoffline">You are offline</div>
Also note that you can make the JS more succinct, although arguably harder to read, by using toggle():
$('#youareoffline').toggle($('#internet_ipaddr').is(':empty'));
you can easily do this using jQuery.
HTML
<label id="label1"></label>
<div id="div1" style="display: none; color: red;">You are off line.</div>
jQuery
var labelText = $("#label1").text();
if (!labelText) {
$("#div1").show();
}
Related
I'm trying to add icons to my navigation (which dynamically changes) via JavaScript.
Here is my code (or JSFiddle):
var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', '');
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
But it is not working, why? When tried to edit data-icon attribute manually, icon appears. Otherwise just unicode of icon.
HTML entities don't have any meaning in CSS. If you want to follow that path you need to decode it first:
var icon = document.querySelector('#icon');
var tmp = document.createElement("span");
tmp.innerHTML = '';
icon.setAttribute('data-icon', tmp.innerText);
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
... or, alternatively, just type character as-is (as long as your application is written in UTF-8):
var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', '†');
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
Last but not least, CSS also accepts escape sequences but you need to use the appropriate syntax. This approach, however, does not seem to work for your specific character:
var icon = document.querySelector('#icon');
// Brackets added for visibility, not part of the syntax
icon.setAttribute('data-icon', '(\u0086)(\u2020)');
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
I presume it's related to the fact that U+2020 'DAGGER' (that works fine) is a regular character but the one you're using U+0086 'START OF SELECTED AREA' (which doesn't show) is a control character. As you mention in a follow-up comment, you're using FontAwesome and such libraries provide custom fonts that map certain code points to display icons (though they normally use private areas to avoid conflicts).
That is obviously because setAttribute is escaping your special characters...and anyway you need to use CSS encoded icons and not an HTML entity. use this convertor:
→ \0086
I would suggest working with meaningful names instead of hard-coded writing the icon's code into an attribute.
For example:
var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', 'icon-heart');
[data-icon=icon-heart]{
content:'\2764';
}
(better that all your icons elements will have a shared class which shared properties)
Encoding minefield
See this StackOverflow answer for more details.
Answer updated (see comments and edits).
In short, I recommend using the character instead of any method of encoding it. It will be vital in this case that your HTML files are correctly encoded and that they properly inform browsers what the encoding is.
var js = document.querySelectorAll( ".js" );
js[ 0 ].setAttribute( "data-icon", "\u0086" );
js[ 1 ].setAttribute( "data-icon", "†" );
.css:after {
content: "\86";
color: red;
}
.css.char:after {
content: "†";
color: blue;
}
.data:after {
content: attr( data-icon );
}
.js:after {
content: attr( data-icon );
}
.red:after {
color: red;
}
.blue:after {
color: blue;
}
<div class="css">hard coded css content</div>
<div class="css char">hard coded css content char</div>
<br>
<div class="data red" data-icon="">hard coded data-icon</div>
<div class="data blue" data-icon="†">hard coded data-icon char</div>
<br>
<div class="js red">data-icon by js</div>
<div class="js blue">data-icon by js char</div>
I have a small piece of code, which I would like to extend with in line editting possibilities:
HTML:
<h1>Schedule <label ng-click="modifyText(index)">{{th.schedules[index].label}} </label>
</h1>
JS:
$scope.modifyText = function(index) {
this.th.schedules[index].label = 'modifiedtext';
};
Hence I would like to be able to click {{th.schedules[index].label}}, modify it inline to the string: "modifiedtext", and save it.
How can I do that?
Thank you.
In order to edit a label inline, you would probably have to use the contentEditable attribute since it isn't directly an editable element. If you give it an ng-model changing that data could be easier but you will still have to make a UI for actually editing it.
Instead I made an example using a text input and some simple styling to make it seem as though it isn't a text input when it isn't focused
http://jsfiddle.net/yrakrj48/
//-- HTML
<body ng-app="TestApp">
<div ng-controller="TestController">
<input ng-class="editing ? 'hasBorder' : 'noBorder'" type="text" ng-model="myLabel" ng-focus="editing = true" />
<button ng-if="editing" ng-click="saveEdit()">done</button>
</div>
</body>
//-- JS
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope) {
$scope.myLabel = 'this is a label';
$scope.saveEdit = function() {
$scope.editing = false;
};
});
//-- CSS
.hasBorder {
border:1px solid #666;
}
.noBorder {
border:none;
}
You should look into directives because creating one would be easy and I am sure one already exists somewhere out on github
I think you use. contenteditable=true
<div contenteditable=true>
I am Editable
</div>
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
Searched a long time to find a solution, but can't find one specific to my needs, so apologies if I've missed something.
On my Wordpress site I have a page with a button, which in order to follow the link of that button a checkbox needs to be checked. This is the code for it...
<form action="#"><input onchange="toggleAccept()" id="agreeCheckbox" type="checkbox" /><label for="agreeCheckbox">I agree to the terms</label></form>
<img src="button.png"/>
There's also some code handling this in the head:
<script type="text/javascript">
function toggleAccept() {
var acceptLink = document.getElementById("accept");
var agreeCheckbox = document.getElementById("agreeCheckbox");
if (agreeCheckbox.checked) {
acceptLink.onclick=function() {
window.location=this.href + "&cbrblaccpt=true";
return false;
}
} else {
acceptLink.onclick=function() {
mustAccept();
return false;
}
}
}
function mustAccept() {
window.alert("Please check the box and agree to the payment terms of this recurring product.");
}
cbrblaccpt
</script>
Basically, if someone tries to click the bottom without checking the box, the above popup appears. Once they check the box, they are taken to the button's link.
The issue I'm having is the TinyMCE is removing the "onchange" and "onclick" parts of the code. I'm guessing because it doesn't like inline Java being there.
After a lot of looking around it seems to me that the ideal solution is to handle this with jQuery in a separate file, but I have absolutely no idea how to do that.
If someone could help in that regard, or perhaps offer another work around then I'm all ears.
Thanks a lot
Well... yes you can handle it with pure jQuery.
I've made an example for you:
REMEMBER to add the jQuery library to your document, just before this <script> and if possible, just before </body> closing HTML tag :D
jQuery:
<script>
$(document).ready(function () {
var agree = $("#accept"); //we cache the element, dont worry
$("#agreeCheckbox").click(function () {
var checked_status = this.checked;
if (checked_status === true) {
agree.removeAttr("disabled");
} else {
agree.attr("disabled", "disabled");
}
});
//we convert the button into an anchor
agree.click(function () {
window.location = $(this).data("href") + "&cbrblaccpt=true";
});
});
</script>
CSS: Because we are using a button instead of an anchor (<a></a>)
#accept {
background: url(http://goo.gl/kCsKU3) center top no-repeat;
color: #FFF;
display: block;
width: 200px;
height: 44px;
border:none;
outline: none;
cursor: pointer;
}
#accept:disabled {
opacity: 0.6;
}
#accept:active {
margin-top:2px;
}
And finally, the HTML: Note we're using data-href attribute for the link instead of a simple hrefbecause this is a button, not an anchor anymore.
<input id="agreeCheckbox" type="checkbox" />
<label for="agreeCheckbox">I agree to the terms</label>
<button data-href="link/?cbur=a" id="accept" disabled="disabled"></button>
JsFiddle: http://jsfiddle.net/n2zej2cg/
I need to write a function that will search all the content in my HTML page for a specific string, and if it finds it then change the color of the text.
Is this possible?
Thanks
You could do that :
CSS :
.someclass {
color: red;
}
Javascript :
$('p:contains('+yourstring+')', document.body).each(function(){
$(this).html($(this).html().replace(
new RegExp(yourstring, 'g'), '<span class=someclass>'+yourstring+'</span>'
));
});
Note that this would make problems if yourstring is in a tag or an attribute.
Demonstration
Be careful to run this code before you attach handlers to your paragraphs (or the elements inside which could contain yourstring, for example links).
The problem with dystroy's answer is that it will overwrite the entire HTML, so if you have any handlers within a node containing your text, they will be removed.
The correct solution is to use text ranges to update only the text itself, not all of the HTML around it. See Highlight text range using JavaScript
And for fun, there is a built-in method window.find that works in FF and Chrome. It's not in the standard though and will only find one at a time. Just like ctrl+f.
window.find("anything");
JQuery Find and change style of a string >> Only Copy Paste and run :)
$('#seabutton').click(function()
{
var sea=$('#search').val();
var cont=$('p').val();
alert(cont);
$('p:contains('+sea+')').each(function()
{
/* $(this).html($(this).html().replace(new RegExp(sea, 'g'),'<span class=someclass>'+sea+'</span>'));
*/ $(this).html($(this).html().replace(
new RegExp(sea, 'i'), '<span class=someclass>'+sea+'</span>'
));
});
});
$('p').click(function()
{
$(".someclass").css("color", "black");
});
$('#search').blur(function()
{
$(".someclass").css("color", "black");
});
})
</script>
<style type="text/css">
.someclass {
color: red;
}
</style>
</head>
<body>
<!-- Select Country:<select id="country" name="country">
</select>
<table id="state" border="1">
</table> -->
<br>
Enter Text:<input type="text" id="search"/><input type="button" id="seabutton" value="Search"/>
<div id="serach">
<p>This is ankush Dapke
</p>
</div>
</body>
</html>