Javascript not updating text within a div - javascript

I must be daft, but the javascript is not changing the containing div text as I would expect once the div is clicked:
favourite.onclick = function() {
loadXMLDoc('indexFavourite');
var linkclass = favourite.className;
if(linkclass == 'favouriteOption')
favourite.className = 'favouriteOptionActive',
favourite.className.update("New text");
else
favourite.className = 'favouriteOption';
}

Your syntax is way off, missing bracket and whatnot
favourite.onclick = function() {
loadXMLDoc('indexFavourite');
var linkclass = favourite.className;
if(linkclass == 'favouriteOption') {
favourite.className = 'favouriteOptionActive',
favourite.innerHTML="New text";
}
else {
favourite.className = 'favouriteOption';
}
}

What you are doing here is changing the class of a div (probably). And even this is kinda wrong. I mean
favourite.className = 'favouriteOptionActive',
favourite.className.update("New text");
should actually produce an error, because the string favouriteOptionActive doesn't have a method update. It could have only if you patch the String.prototype.
If you want to change the div's text you should use div.innerHTML or div.innerText.

favorite.text('New text') will set the text
note this will work if using jQuery, my bad!

Related

create a class for dynamic div based on mouse event

I'm creating a dynamic div using javascript. and here I want to assign the class name dynamically. like the below conditions.
on mouse hover set the class to a
on mouse click set the class to b
else set it to class c
my code is as below.
var elementRange = document.getElementById("div");
var elementSpan = document.createElement("span");
if (elementSpan.onmouseover) {
elementSpan.className = "a";
} else if (elementSpan.onclick) {
elementSpan.className = "b";
} else {
elementSpan.className = "c";
}
elementRange.appendChild(elementSpan);
<div id="div"></div>
here when I run this, the mouse hover/click is not working, only the default one is up. please let me know how can I do this.
Also, I use the only javascript.
Thanks
You need bind EventListener at first also by if else statement not work for event as a event switcher how way you tried:
var elementRange = document.getElementById("div");
var elementSpan = document.createElement("span");
elementSpan.addEventListener("click", function(){
elementSpan.className = "a";
});
elementSpan.addEventListener("mouseover", function(){
elementSpan.className = "b";
});
elementSpan.addEventListener("mouseout", function(){
elementSpan.className = "c";
});
elementSpan.innerHTML = "Lorem Ipsum"; //I added this line at least make span visible purpose
elementRange.appendChild(elementSpan);
You could use one of the methods in Element.classList
elementSpan.classList.add('a');
elementSpan.classList.remove('b');
elementSpan.classList.toggle('a');
more here https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
but as #Archer mentioned you are probably going at it the wrong way
here when I run this, the mouse hover/click is not working, only the default one is up.
Because you have not registered any events yet.
You have just created an element and checking immediately that they have any events registered.
This is not the way to set the class name. You have to listen to the event and do stuff in callback .For ex
elementSpan.addEventListener("click", function(){
elementSpan.className = "b";
});
elementSpan.addEventListener("mouseover", function(){
elementSpan.className = "a";
});
Or even you can use CSS pseudo selectors to do so.
Here is my solution:
elementSpan.innerHTML="Hello";
elementSpan.onmouseout=function()
{
this.className="c";
}
elementSpan.onmouseover=function()
{
this.className="a";
}
elementSpan.onclick=function()
{
this.className="b";
}
You may refer here for detail.

JQuery detecting empty p tag

I need to ask for some help with this one so here goes...
I'm creating a WYSIWYG editor using a contenteditable textarea. It automatically creates paragraphs and you can also add in subtitles.
What I would like to be able to do is when the button #addStorySubtitle is clicked, if the currently selected p tag is empty or only contains a zero width space ​, then it will be replaced with the contents of innerDivSubtitle. However, if the p tag has content, use innerDivSubtitle to create a new block level element underneath.
The part I seem to be having trouble with is detecting is the p tag is empty.
Thanks all!
$('#addStorySubtitle').click(function(e){
var innerDivSubtitle = $('<div class="addStorySubtitleWrap" contenteditable="false"><span class="removeStorySubtitle"></span><textarea name="addstorysubtitle" class="addStorySubtitle autoSize" placeholder="Really good subtitle" contenteditable="true"></textarea></div><p>​<p>');
var sel = window.getSelection();
if ($(sel.anchorNode.parentNode) === "") {
alert('empty'); //just for help
$(sel.anchorNode.parentNode).replaceWith(innerDivSubtitle);
} else {
alert('not empty'); //just for help
$(sel.anchorNode.parentNode).after(innerDivSubtitle);
}
});
UPDATE
Thanks for all of your helpful replies!
It turns out that the zero width space detection was causing the issue and I had to use unicode to detect it. Here's what I did to fix it...
var nodCon = $(sel.anchorNode.parentNode).html();
if (nodCon === "" || nodCon === "\u200b"){
alert('empty');
}
I hope this will help you?
if($('p').html() == "" || $('p').html == "​"){
//Do something
}
You can check whether the element has content like this:
checkElementContents(document.getElementById('p1'));
checkElementContents(document.getElementById('p2'));
function checkElementContents(element) {
if (element.innerHTML) {
console.log(element.id + " is not empty");
} else {
console.log(element.id + " is empty");
}
};
<p id="p1"></p>
<p id="p2"> </p>
Be careful with spaces, carriage return etc...
function isEmpty(ele)
{
var count = ele.html().replace(/\s*/, '');
if(count>0)
return false;
return true;
}
console.log(isEmpty($('p')));
Check if empty the following way:
if ($("Your p tag").val().length == 0) { /* Empty */ }

How do i clear text out of a div using javascript

Okay here is what i have:
<script type="text/javascript">
var where = document.getElementById("info")
var texts = false;
function clear() {
where.innerHTML = "";
};
function dostuff(what) {
if(where.style.value === ""){
var comm = document.createTextNode(what);
where.appendChild(comm);
}else {
clear();
}
};
</script>
the id "info" is a div
this is basically a vertical navigation bar that shows tooltips in a div under the buttons when you hover over them.
So I want to first check if the div has no value then if it doesn't then it will append text into it, else it will clear the text but i also want it to append the text after it clears. I'm not sure how to do this and help would be appreciated. thanks
Since you want to clear the item anyways and put your new text in, why even bothering with the conditional? You could just as easily do:
function dostuff(what) {
where.innerHTML = what;
};
Working example

Issue with the contains method and highlighting elements

I want to highlight an element that contains a string written in a textbox. This is the part of the code that's supposed to do it:
$("#rightContainer .magnifier").click(function () {
var a = $("#searchBox").val();
if (a != "") {
var foundin = $('div:contains(a)');
foundin.addClass("highlighted");
alert(a);
}
})
The problem is that the whole page gets highlighted. I'm assuming this happens because I have a main container which has its children containers, so the contains method selects the whole main container. Is this the case or is it because of something else, and does anyone have a better way of doing this? Thanks in advance.
The :contains selector will return any element which contains the text you're searching for, in this case "a". This has nothing to do with the variable named a. Perhaps you meant to do something like this:
$("#rightContainer .magnifier").click(function () {
var a = $("#searchBox").val();
if (a != "")
{
var foundin = $("div:contains('" + a + "')");
foundin.addClass("highlighted");
alert(a);
}
})
If I understand correctly, you only want the div highlighted which is wrapping that searchbox and not any other div. Use closest() to find that div.
$("#rightContainer .magnifier").click(function () {
var a = $("#searchBox").val();
if (a != "")
{
$("#searchBox").closest('div').addClass('highlighted');
}
})

How to change button text or link text in JavaScript?

I have this HTML button:
<button id="myButton" onClick="lock(); toggleText(this.id);">Lock</button>
And this is my toggleText JavaScript function:
function toggleText(button_id)
{
if (document.getElementById('button_id').text == "Lock")
{
document.getElementById('button_id').text = "Unlock";
}
else
{
document.getElementById('button_id').text = "Lock";
}
}
As far as I know, button text (<button id="myButton">Lock</button>) is just like any link text
(Lock). So the fact that it's a button doesn't matter. However, I can't access the button text and change it.
I tried ('button_id'), (button_id), == "Lock", == 'Lock', but nothing works.
How can I access and change a button text (not value) or a link text?
Change .text to .textContent to get/set the text content.
Or since you're dealing with a single text node, use .firstChild.data in the same manner.
Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById.
function toggleText(button_id)
{
var el = document.getElementById(button_id);
if (el.firstChild.data == "Lock")
{
el.firstChild.data = "Unlock";
}
else
{
el.firstChild.data = "Lock";
}
}
Or even more compact like this:
function toggleText(button_id) {
var text = document.getElementById(button_id).firstChild;
text.data = text.data == "Lock" ? "Unlock" : "Lock";
}
document.getElementById(button_id).innerHTML = 'Lock';
You can simply use:
document.getElementById(button_id).innerText = 'Your text here';
If you want to use HTML formatting, use the innerHTML property instead.
Remove Quote. and use innerText instead of text
function toggleText(button_id)
{ //-----\/ 'button_id' - > button_id
if (document.getElementById(button_id).innerText == "Lock")
{
document.getElementById(button_id).innerText = "Unlock";
}
else
{
document.getElementById(button_id).innerText = "Lock";
}
}

Categories