I have links on a page that I wanted to add an ID Anchor too. This code I have works fine:
window.onload = function() {
$('#main > div > ul > li > a').attr('href',function(i,str) {
return str + '#myAnchor';
});
};
But sometimes because of the way the page is set up tracking gets added to the links so what is happening at the moment is I get http://www.myurl.com/#someannoyingtracking#myAnchor which doesn't anchor. How can I insert the anchor in between the URL or always after the ".com/" Like this: http://www.myurl.com/#myAnchor#someannoyingtracking
This will insert an anchor before an annoying tracking anchor or at the end of the URL:
$('#main > div > ul > li > a').attr('href', function(i,str) {
return str.replace(/(\#.+)|($)/, '#myAnchor$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div>
<ul>
<li>Has anchor
<li>No anchor
</ul>
</div>
</div>
Piggybacking on Rick Hitchcock's answer, but regex-free:
$('#main > div > ul > li > a').each(function(index, elem) {
elem.hash = '#myAnchor' + elem.hash;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div>
<ul>
<li>Has anchor
<li>No anchor
</ul>
</div>
</div>
You can use replace for that:
window.onload = function() {
$('#main > div > ul > li > a').attr('href',function(i, str) {
if (str.indexOf('#') > -1) {
return str.replace('#', '#myAnchor');
} else {
return str + '#myAnchor';
}
});
};
Related
I am trying to filter and mark word from a webpage, and Sajeeb Ahamed graciously assisted me with a piece of code that functions exactly as I wanted,however when I add and other element tags such as an list item or heading tag when I clear the input box it displays the HTML markup.
$(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV>*").map(function() {
var el = $(this);
var content = el.html().replace(/(<span class="highlighted">)|(<\/span>)/g, "");
el.html(content);
var hasText = el.text().toLowerCase().indexOf(value) > -1;
el.toggle(hasText);
if (hasText) {
// escape value for use in regex
var textRegex = new RegExp(value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
el.html(content.replace(textRegex, '<span class="highlighted">$&</span>'));
}
});
});
});
.highlighted {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" />
<!-- the new search -->
<div id="myDIV">
<p>This is a test</p>
<ul>
<li>This is a list item</li>
<li>This is a another list item</li>
</ul>
This is a link
</div>
This the code, it will only accept a paragraph tag. Does anybody have any idea why?
Thanks
It works with any element inside the element with id 'myDIV' at first level (not deep),because you are using this selector $("#myDIV>*"). Be sure that your tag is inside this rule.
UPDATE WITH NEW INFORMATION
$(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
// Remove all class="highlighted" inside #myDIV
$("#myDIV").html($("#myDIV").html().replace(/(<span class="highlighted">)|(<\/span>)/g, ""))
$("#myDIV *").map(function() {
var el = $(this);
// Only in deep children aplly your logic
if (el.children().length == 0) {
var content = el.html().replace(/(<span class="highlighted">)|(<\/span>)/g, "");
el.html(content);
var hasText = el.text().toLowerCase().indexOf(value) > -1;
el.toggle(hasText);
if (hasText) {
// escape value for use in regex
var textRegex = new RegExp(value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
el.html(content.replace(textRegex, '<span class="highlighted">$&</span>'));
}
}
});
});
});
.highlighted {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" />
<!-- the new search -->
<div id="myDIV">
<p>This is a test</p>
<ul>
<li>This is a list item</li>
<li>This is a another list item</li>
</ul>
This is a link
</div>
You need to apply changes on deep children. and remove class highlight on begining
Most clean approach, rest div and start again. So before the start, I took the snapshot of div and save it. Every time data change I reconstruct it. Easy to understand and scale.
Suggestion: The UI should be data-driven. Not HTML/content-driven. You can create a list of data and construct on every change.
Checkout my second example
Do not mutate state/UI[React]
$(document).ready(function () {
const div = $("#myDIV").html();
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myDIV").html(div); //Reset
const p = $("#myDIV p");
var hasText = p.text().toLowerCase().indexOf(value) > -1;
hasText && highlight(p, value);
$("#myDIV li").map(function () {
var el = $(this);
var hasText = el.text().toLowerCase().indexOf(value) > -1;
if (hasText) {
highlight(el, value);
} else {
el.remove();
}
});
});
});
function highlight(elm, text) {
elm.html(
elm
.html()
.replace(new RegExp(`(${text})`), '<span class="highlighted">$1</span>')
);
}
.highlighted {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" />
<!-- the new search -->
<div id="myDIV">
<p>This is a test</p>
<ul>
<li>This is a list item</li>
<li>This is a another list item</li>
</ul>
This is a link
</div>
Using data-driven approach.
$(document).ready(function () {
const list = ["This is a list item", "This is a another list item"];
function buildUi(keyword) {
$("#filter .list").html("")
list.forEach((text) => {
if (!keyword || text.toLowerCase().indexOf(keyword) !== -1) {
text = text.replace(
new RegExp(`(${keyword})`),
'<span class="highlighted">$1</span>'
);
} else {
return;
}
const li = $(`<li>${text}</li>`);
$("#filter .list").append(li);
});
}
buildUi("");
$("#myInput").on("keyup", function () {
const keyword = $(this).val().toLowerCase()
buildUi(keyword)
});
});
.highlighted {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" />
<!-- the new search -->
<div id="filter">
<p>This is a test</p>
<ul class="list">
</ul>
This is a link
</div>
Hi guys so i found what i was looking for, thanks to the assistance of the great guys here and a lot of head banging, this script works for a local webpage search and filter, it must run in conjunction with jsquery mini and the hilitor.js file. This ought to be worth something to somebody out there. Happy coding guys.
<script src="../js/hilitor.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
window.addEventListener("DOMContentLoaded", function(e) {
var myHilitor2 = new Hilitor("playground");
myHilitor2.setMatchType("left");
document.getElementById("keywords").addEventListener("keyup", function(e) {
myHilitor2.apply(this.value);
}, false);
}, false);
$(document).ready(function(){
$("#keywords").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#playground *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<label>Search And Filter</label><input id="keywords" type="text" placeholder="Search And Filter.." onKeyDown="if(event.keyCode === 32) return false;">
<div id="playground" >
<ul>
<li>Hey diddle diddle,</li>
<li>The cat and the fiddle,</li>
<li>The cow jumped over the moon.</li>
<li>The little dog laughed to see such sport,</li>
<li>And the dish ran away with the spoon.</li>
</ul>
</div>
Add text to unordered list on keyup event of textarea and there should't be any li when there is no text in textarea
HTML:
<textarea id="activityText"></textarea>
<div id="qwe">
<ul>
<li id="textFromTextArea"></li>
</ul>
</div>
jQuery:
$("#activityText").keyup(function () {
$("#textFromTextArea").text($("#activityText").val());
})
If there is no text in textarea then there should't be any list, can it be possible with jQuery
https://ibb.co/gjpDTL
Option 1:
I moved id from li to ul. I removed li element since you want to do not show marker.
<div id="qwe">
<ul id="textFromTextArea">
</ul>
</div>
<textarea id="ActivityText"></textarea>
and js:
$("#ActivityText").keyup(function () {
var val = $(this).val();
if($("#textFromTextArea li").length===0) {
var $li = $("<li>");
$li.html(val);
$("#textFromTextArea").append($li);
} else {
$("#textFromTextArea li").html(val);
}
});
Option 2:
Show/hide li element, preserve actual HTML you wrote but I add a CSS class hide
<div id="qwe">
<ul>
<li id="textFromTextArea" class="hide"></li>
</ul>
</div>
<textarea id="ActivityText"></textarea>
css
.hide {
display: none;
}
and js
$("#ActivityText").keyup(function () {
var val = $(this).val();
var $li = $("#textFromTextArea");
if(val.length === 0) {
$li.addClass("hide");
} else {
$li.removeClass("hide");
}
$li.html(val);
});
Try this
HTML:
<textarea id="activityText"></textarea>
<div id="qwe">
<ul id="list">
</ul>
</div>
jQuery:
var textval = '';
$("#activityText").on("keyup", function() {
textval = $(this).val();
if (textval.length > 0) {
$("#list").html('<li>' + textval + '</li>');
} else {
$("#list").empty();
}
});
I want to change color backgroud of tag in my code depending on URL. If url contains Suisse, it changes the background color to green for the tag #switch-univers li a.bilgroup
JS
if (window.location.href.indexOf("Suisse") > -1) {
$('#switch-univers li a.bilgroup').css({ backgroundColor, 'green' });
} else if window.location.href.indexOf("Sales") > -1) {
$('#switch-univers li a.sales').css({ backgroundColor, 'blue' });
} else if (window.location.href.indexOf("My%20desktop") > -1) {
$('#switch-univers li a.lifebil').css({ backgroundColor, 'pink' });
}
And My HTML is :
<body>
<Div id= « switch-univers » >
<li><a class=“bilgroup“>Suisse</a></li>
<li><a class=“sales“>Sales</a></li>
<li><a class=“lifebil“>My desktop</a>
</li>
</div>
</body>
Nothing happen...
Any Suggestions
Try this.
<div id="switch-univers">
<li><a class="bilgroup">Suisse</a></li>
<li><a class="sales">Sales</a></li>
<li><a class="lifebil">My desktop</a>
</li>
</div>
JQuery:
$(document).ready(function(){
if (window.location.href.indexOf("Suisse") > -1) {
$('#switch-univers li a.bilgroup').css('background-color', 'green');
} else if window.location.href.indexOf("Sales") > -1) {
$('#switch-univers li a.sales').css('background-color', 'blue');
} else if (window.location.href.indexOf("My%20desktop") > -1) {
$('#switch-univers li a.lifebil').css('background-color', 'pink');
}
});
I use this script
$(function () {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
$('.tree li.parent_li > span').on('click', function (e) {
var children = $(this).parent('li.parent_li').find(' > ul > li');
if (children.is(":visible")) {
children.hide('fast');
$(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
} else {
children.show('fast');
$(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
}
e.stopPropagation();
});
http://jsfiddle.net/jhfrench/GpdgF/
for recursive collapsible menu. It works perfectly. But I need the menu collapsed initially that is when the page load and expand only on click.
My JS knowledge is weak. But i tried using toggle(); and hide(); , it results in collapsed and doesnt expand on click
Below is recursive php code
<?php
function listroles($roles)
{
?>
<ul>
<?php
foreach($roles as $role)
{
?>
<li>
<span><i class="icon-plus "></i> Parent</span> <?php echo $role['category']->name; ?>
<?php
if ( ! empty($role['children']))
{
listroles($role['children']);
}
?>
</li>
<?php
}
?>
</ul>
<?php
}
listroles($this->categories_menu);
?>
You can add a css rule to hide the child li elements at the start
.tree li ul > li {
display: none;
}
Demo: Fiddle
or hide the child li element on page load
$(function () {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
//hide the child li elements
$('.tree li ul > li').hide();
$('.tree li.parent_li > span').on('click', function (e) {
var children = $(this).parent('li.parent_li').find(' > ul > li');
if (children.is(":visible")) {
children.hide('fast');
$(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
} else {
children.show('fast');
$(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
}
e.stopPropagation();
});
});
Demo: Fiddle
The easiest way to accomplish what you want is to run the click() handler once.
$(function () {
$('.tree li.parent_li > span').on('click', function (e) {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
//blah blah blah
e.stopPropagation();
}).click();
});
edit: forgot some code
ok so my website has a navigation with an id #nav so I want to activate a tabber based on the click navigation list. The navigation #nav has an html like this:-
<ul id ="nav">
<li>Fred</li>
<li>Thom</li>
<li>Kay</li>
</ul>
now when Fred is clicked from the navigation, I want to activate this on the tabber which has an html like this
<ul class="tabs">
<li>Fred</li>
<li>Thom</li>
<li>Kay</li>
</ul>
and tab content like this:-
<div id="tab1" class="tab_content">Lorem</div>
<div id="tab2" class="tab_content">Ipsum</div>
<div id="tab3" class="tab_content">Dolor</div>
so I wrote the following line of jquery
$("#nav li").click(function() {
var hash = location.hash;
var sel = $("ul.tabs li a[href='" + hash + "'], ul#tabs li a[href='" + hash + "']");
if (sel.length) {
sel.addClass("active").parent().addClass("active"); //Activate tab
$(hash).show();
}
but it's not working :( what am I doing wrong guys?
Try
$(function(){
$("#nav li").click(function(event) {
var hash = $('a', this).attr('href');
var sel = $("ul.tabs li a[href='#" + hash + "']");
sel.trigger('click')
return false;
});
$('.tab_content').hide();
var tabllis = $('ul.tabs li');
tabllis.click(function(){
var $this = $(this).addClass('active');
var hash = $('a', this).attr('href');
tabllis.not($this).removeClass('active');
$('.tab_content').hide();
$(hash).show();
return false;
});
});
Demo: Plunker