If URL contains string then run jQuery function? - javascript

On my website id like to run a jQuery function if my url contains the word 'test'
All im trying to do is if my url contains the 'rest' string then add a margin to an element on the page?
Ive added a jSfiddle to try and show what Ive done so far.
$(document).ready(function(){
// How can I check to see if my url contains the word 'TEST' then run the below function?
$('.block-widget').css('margin-top, 252px')
});

Use window.location to get the current location url..
Based on the condition you can then apply the margin top property.
$(document).ready(function(){
var pathname = window.location.pathname;
if(pathname.indexOf('text') > -1){
$('.block-widget').css('margin-top, 252px');
}
});

$(document).ready(function(){
if (document.url.match(/test/g)){
$('.block-widget').css('margin-top, 252px')
}
});

Take a look at this link that contains details that you need to know about URL.
https://developer.mozilla.org/en-US/docs/DOM/window.location
$(document).ready(function(){
if (window.location.href.indexOf('rest') >= 0) {
$('.block-widget').css('margin-top, 252px')
}
});

Get the path name:
var pathname = window.location.pathname;
Then check if it contains "TEST".
if (pathname.toLowerCase().indexOf("test") >= 0)

try this
$(document).ready(function(){
var patt=/test/g;
if(patt.test(window.location.pathname)){
$('.block-widget').css('margin-top, 252px')
}
});

name*='keyword' selector is true option.
<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
Resource: https://api.jquery.com/attribute-contains-selector/

Related

Trim partial link in jQuery

I am trying to remove the start of a link in jQuery. I have tried to inject the following function but it doesn't work. What am I doing wrong?
JS
$(function() {
$('link-active').each(function() {
$(this).attr('href').remove('http://www.linkplus.com/xQWE=');
});
});
HTML
<td class="block">
<a class="link-active"
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>
When you're trying to search for classes, make use of dot (.), $('link-active') should be $('.link-active').
About .remove(): this one will remove one element of the DOM; not applicable in this case.
Solution: You will need to use .attr() to return AND update the href attribute of your tag, .replace() method should help.
$(function() {
$('.link-active').each(function() {
let href = $(this).attr('href'); //returns href value
let removableUrl = 'http://www.linkplus.com/xQWE=';
href = href.replace(removableUrl, ''); //replace the url you don't want with ''
$(this).attr('href', href); //update href value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="block">
<a class="link-active"
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>
Note: There's other methods to separate the url you don't want (if the url stay in the same format), check for:
.substring(): href = href.substring(removableUrl.length);
.split(): href = href.split('=')[1];
.replace() with regex: href = href.replace(/.*\=/,'');
Amend $('link-active') to $('.link-active').
First thing is While representing a class in jQuery try using dot notation..
$(function() {
$('.link-active').each(function() {
$(this).attr('href').remove('http://www.linkplus.com/xQWE=');
});
});
It's convenient to use attr method like this:
$(function() {
$('.link-active').attr('href', function(i, href) {
return href.replace('http://www.linkplus.com/xQWE=', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link-active" href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
Change your code on line 3 to
$(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));
Full code should be
$(function() {
$('link-active').each(function() {
$(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));
});
});
remove is not being used correctly here, as that method is meant to remove elements from the DOM and accepts a selector string as its argument.
Try something like this instead:
$(function() {
$('.link-active').each(function() {
var href = $(this).attr('href');
var strToReplace = 'http://www.linkplus.com/xQWE=';
$(this).attr('href', href.replace(strToReplace, ""));
});
});
Above we use replace to replace the start of the link with an empty string.
You have to get the string, replace it and then set it again.
Something like this:
$(function() {
$('link-active').each(function() {
replacement = 'http://www.linkplus.com/xQWE=';
url = $(this).attr('href');
$(this).attr('href', url.replace(replacement, ''));
});
});

Transforming href links on pageload using jquery

I need to transform all the links(href values) to specific format
for example - if a page has a link http://www.exampledomain.com i want to convert its href to http://url.com/xyz?http://www.example.com
Below is the jquery i am using for this task (Note that i am new to jquery)
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
});
});
But above script is converting all the links of the website and my navigational links are also getting changed. How can we filter to change only the href's of links that contain 'http' and 'www'?
I know some kind of regex can be used for this purpose. Thanks in advance!
I thinks you should extract all internal links.
You can check if value match your criteria (http://www):
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.indexOf("http:\\www") > -1 ){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
But it will be better to extract all the internal links:
var myHost = new RegExp(location.host);
$('a').each(function(){
var value = $(this).attr('href');
if(!(myHost.test(value))){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
The last and better option is to take just the external links: ( if you don't have to do anything to the internal)
$( document ).ready(function() {
$("a[href^='http']").each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});
You could try for the following code
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.match("http://www.*"))
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});
You have to make sure that no navigation link contain
"http://www"
in them. Use relative links where you dont want to replace the href.
Or you could give a class to all anchor tags which you want to modify accordingly
Demo Fiddle
Check the anchor tag's href using element inspector
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});
using window.location.host and test
Modified from this article at CSS-Tricks.com
One approach:
// selects all 'a' elements:
$('a')
// sets the 'href' attribute, using the anonymous function to iterate over each
// 'a' element:
.attr('href', function(i,oldhref){
// i: the index of the current element in the returned collection,
// oldhref: the value of the 'href' before manipulation by the function.
// if 'exampledomain.com' features in the hostname of the link we
// manipulate the 'href' as required, otherwise we simply set the 'href'
// to its original value:
return this.hostname.indexOf('exampledomain.com') > -1 ? 'www.url.com/xyz?' + oldhref : oldhref;
});
JS Fiddle demo.
References:
JavaScript:
String.prototype.indexOf().
jQuery:
attr().
You can check the link is external or internal then you can add the additional effort.
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if($(this[href^='http'])
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});

Remove the # from the variable

I have this script:
Menu item
I can not edit the html. Only the js. This is my js:
// Click
$('.next-content').click(function() {
var url = $(this).attr('href');
console.log(url);
});
When i click on the a button. I get the variable. The href in the variable. The variable is #extensive. But, how can i remove the # from the variable?
Thanks for help
var url = $(this).attr('href').substring(1);
You can replace the '#' character
url.replace('#','')
or substring
url.substring(1)
Can't you just do
// Click
$('.next-content').click(function() {
var url = $(this).attr('href');
url=url.replace("#","");
console.log(url);
});
You can google it easily...
var url = $(this).attr('href').substr(1);
I'm unsure really.
This may help. I would have said replace would have been your best option:
url.replace('#', '');

Append to a.href id from input field

I am trying to append to a link with id a value that is entered from the input text field. I came this far searching stackoverflow but id doesn't work!
<script type="text/javascript">
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
});
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code='.text(value);
});
});
</script>
and this is how the html looks like
<form>
<fieldset>
<input id="txt_name" type="text" value="discount" />
</fieldset>
</form>
<a id="coupon_link" href="https://www.e-junkie.com/ecom/gb.php?c=cart&i=XXXXXX&cl=YYYYYY&ejc=2" target="ej_ejc" class="ec_ejc_thkbx" onClick="javascript:return EJEJC_lc(this);"><img src="http://www.e-junkie.com/ej/ej_add_to_cart.gif" border="0" alt="Add to Cart"/></a>
You probably meant this:
$(function() {
$("#coupon_link").on('click', function(e) {
e.preventDefault(); // apparently not needed
location.href = $(this).attr('href') + '&discount_code=' + encodeURIComponent($('#txt_name').val());
});
});
You don't have to update the value of #txt_name on keypress; you only have to use the value when the link is pressed.
Fix your code like this :
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
var link = $("#coupon_link");
var originalHref = link.attr('originalHref');
if (!originalHref) {
originalHref = link.attr("href");
link.attr("originalHref", originalHref)
}
link.attr("href", originalHref + '&discount_code='+value);
});
});
A few things to note :
never add anything to a selector when you're targeting an element by ID
your value variable wasn't in the same scope
the return of val can be directly concatenated, you don't need to try to change it to text
you don't need to pass a function to attr in your case
you're trying to make the href grow with every key stroke. This is a bad idea. The solution I propose is to keep the original href
if you're not sure the original href has yet some parameters (i.e. has '?') you should test it (I let you do that)
Overall a much cleaner solution wouldn't be to change the link but to build the href on click on the link :
$("#coupon_link").click(function(e) {
location = this.href + '&discount_code=' + $('#txt_name').val();
});
Not sure to understand, but it looks like a scope issue try this javascript :
<script type="text/javascript">
jQuery(function(){
var value = 0;
$("#txt_name").keypress(function() {
value = $("#txt_name").val();
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code=' + encodeURIComponent(value);
});
});
});
</script>
Try this:
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href", '&discount_code=' + String(value));
});
});
This isnt working because the href isnt being changed as the function is called before a keypress event is triggered. Look into replacing keypress with blur and update the href when blur() is called
i think you need this:
<script type="text/javascript">
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href",href+'&discount_code='+value.toString);
});
});
</script>
look at href don't know where you have that var, if it is needed ok else remove that
You probably need to change the href when a key has been pressed, not only on page load. To do so you will have to do the replacing of the href inside the keyup function, like so:
$(function(){
var link = $("a#coupon_link");
link.data('href', link.attr("href"));
$("#txt_name").on('keyup', function() {
link.attr("href", link.data('href') + '&discount_code='+ this.value);
});
});
So as to not append the &discount_code=*** several times, you need to store the original href somewhere, like in a data attribute.
this one worked for me getting value from input field and append it to the existing link using jquery.
$('#qty').on('keyup', function() {
var theQty = 0;
theQty = $("#qty").val();
var oldHref=$("a#buybtn").attr("href");
$("a#buybtn").attr("href",oldHref+ '&qty=' + String(theQty));
});

store HTML tag attribute value in a variable using Jquery

I am developing an application using JQuery. This is a fragment of the HTML code I am using:
<MarkNag class="altcheckboxoff" id="markable_38" Azpimark_id="100038">helburua </MarkNag>
<MarkNag class="altcheckboxoff" id="markable_2" Azpimark_id="100002">Oriolek </MarkNag>
<MarkNag class="altcheckboxoff" id="markable_39" Azpimark_id="100039">gas liberalizazioa </MarkNag>
I have the next JQuery script in the HTML page:
<script type='text/javascript'>
$("MarkNag").click(function (){
$(this).toggleClass("highlight");
});
</script>
I would like to know how could I store "markable_39" in a variable if this MarkNag tag was clicked. I guess I should use .data(). But I dont really know how. Any ideas? Thanks
Do it like this
$("MarkNag").click(function ()
{
$(this).toggleClass("highlight");
var IdOfTag = this.id;
//or
IdOfTag = $(this).attr('id');
});
Also, you can just use this.id,
like:
var id = this.id;
Actually, the correct code would be $(this).attr("id").
$("MarkNag").click(function (){
$(this).toggleClass("highlight");
alert(this.id); // Method 1: this.id
alert($(this).attr('id')); // Method 2: $(this).attr('id')
});
here u will get object from where the event occurs
var eventobject = arguments.callee.caller.arguments[0];
here u can access any attribute of currentTarget (in this case id)
var id = $(eventobject.currentTarget).attr("id");

Categories

Resources