How could I hide divs that begin with id "news" but also contain a number like "news1" "news2" etc if the URL hash doesnt contain "news".
like hide if someurl.com/#events. but show any "news" div if someurl.com/news1
need in regular JS
thanks,
Try This:-
$(function(){
var url = window.location.hash;
if(url.indexOf('news') > -1){
$("div[id^='news']").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="news1">News1</div><br>
<div id="news2">news2</div><br>
<div id="news3">news3</div><br>
<div id="event">event</div><br>
Update: (Using Pure JavaScript)
(function() {
var url = window.location.hash;
/* for testing set the hash to 'news' */
url='news';
if(url.indexOf('news') > -1){
var bodyDOM = document.body;
bodyDOM.querySelectorAll("[id^='news']").forEach(function(item, index){
item.style.display='none';
});
}
})();
<div id="news1">News1</div><br>
<div id="news2">news2</div><br>
<div id="news3">news3</div><br>
<div id="event">event</div><br>
The script hasn't been tested. It does these steps:
Looking for the word "#news" in URL. In our case, if there aren't any word.
For each div with the ID "new" or similar
Add a CSS to this div to hide it.
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("#news") < 0) {
$("div[id^='news']").css('display', 'none');
}
});
</script>
If you put a class on all the divs you'd want this apply to, you can do this:
$(document).ready(function() {
$('.CLASSNAME').each(function(i) {
if($(this).val().indexOf('WORD_YOURE_LOOKING_FOR') > -1) {
$(this).css('display', 'none');
}
);
});
Well you can access the hash in a URL like so:
var hash = window.location.hash;
I'm not 100% clear what you want to do at that point. If you wanted to show the news1 div, you'd do this:
if(hash == 'news1') {
$('#news1').show();
}
Try this:
var hash = window.location.hash;
$('[id^="'+hash+'"').hide();
Related
<div class="test-class">
<div class="test-class1" id="test-id1">hello 1</div>
<div class="test-class2" id="test-id2">hello 2</div>
<div class="test-class3" id="test-id3">hello 3</div>
</div>
And I would like to Disable/hide the Second [div] (id="test-id2") , when the page URL contains the string ?fullpost.
So for example: if my URL is http://www.example.com/post_1.html?fullpost then test-id2 div should not be active.
And if the URL is for example only http://www.example.com/post_1.html then test-id2 div should be active.
<script>
let element = document.getElementById("test-id2");
if(window.location.href.search("?fullpost") > -1){
element.parentNode.removeChild(element);
}
</script>
My script is not working.
Try this instead
<script>
let element = document.getElementById("test-id2");
if(window.location.href.includes("?fullpost")){
element.parentNode.removeChild(element);
}
</script>
It looks like when I run it window.location.href.search("?fullpost") naturally gets parsed as a regular expression. So you need to escape the '?'
<script>
let element = document.getElementById("test-id2");
if(window.location.href.search("/?fullpost") > -1){
element.parentNode.removeChild(element);
}
</script>
Another way to do it would be to use includes()
if(window.location.href.includes("?fullpost"))
{
I fixed it using Regex check the next code
var element = document.getElementById("test-id2");
var reg = /(\?|\&)?fullpost/g;
var url = window.location.href;
if (reg.exec(url) !== null) {
element.parentNode.removeChild(element);
}
Here's the full page of the snapshot https://output.jsbin.com/cataxix?fullpost
The regex will check if the URL contains fullpost as the first parameter or wherever it is in the URL as a parameter.
If your URL was like that http://www.example.com/post_1.html?anything&fullpost it will work.
you should use indexOf() instead of search ()
let element = document.getElementById("test-id2");
var url = window.location.href;
if(url.indexOf("?fullpost") > -1)
{
element.parentNode.removeChild(element);
}
add a listener on that element -- you want it to prevent only for a specific page
let ELM = document.getElementById("test-id2");
ELM.addEventListener("click",(ev) => {
if(window.location.href.test(/\?fulpost/)){
//ev.preventDefault(); // for <a></a>
ev.stopImmediatePropagation(); // this will prevent any click_event from execution
}
},true);
How can I hide a article if the name is empty.
I am using some articles on my site to display certain information.
<article name="<?php echo $name[0];?>">
<p>Content</p>
<article>
How can I hide that article if the name is empty or there is another article with the same name?
You can try this (http://jsfiddle.net/v6at2rhj/):
$( document ).ready(function(){
var articles = [];
$("article[name]").each(function(){
if ($(this).attr("name") == "")
{
$(this).hide();
}
else
{
if (articles.indexOf($(this).attr("name")) > -1 )
{
$(this).hide();
}
else
{
articles.push($(this).attr("name"));
}
}
});
});
On page load it finds all articles with the name attribute (empty or not). Then it iterates over them. If the attribute is empty it will hide the element. If not it will check if the name of the element is in the articles array. If so hide the element, if not add it to the array.
[].forEach.call(document.querySelectorAll('article[name=""]'), function(article) {
article.style.display = 'none';
});
This code will look for each article with a blank name attribute, and set it's display to none, effectively hiding it. You could go a step further and remove it from the DOM completely, if you wish.
you should give the article a class for example
and then add this code to your javascript
$(.article-class).on('each',function() {
if ($(this).attr('name')=='')
{
$(this).hide()
}
)};
Try
$("article[name]:has(p:contains('Content'))").hide();
$("article[name]:has(p:contains('Content'))").hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<article name="<?php echo $name[0];?>">
<p>Content</p>
<article>
Here is an example:
$(document).ready(function(){
$('article').each(function (i) {
var name = $(this).attr('name');
var articles = $("article[name='"+ name +"']:visible")
if(name == "" || articles.length > 1)
{
$(this).hide();
}
});
})
Try it out here.
First off I'd like to apologise for asking about something so specific but it's been wracking my brain all day and I'm out of ideas.
I'm using jquery to show and hide elements based on their number suffix ie:
<span></span> will target ->
<div class="content" id="cont-1">This is content</div> and it's working perfectly. I'd like to target another element based on the suffix of another element but I'm failing to. Here's the code:
HTML:
<script src="http://code.jquery.com/jquery.js"></script>
1
2
3
<div class="content" id="cont-1"><p>This is content</p></div>
<div class="content" id="cont-2"><p>This is content</p></div>
<div class="content" id="cont-3">
<div class="child" id="child-11"><p>This is the first child</p></div>
<div class="child" id="child-12"><p>This is the second child</p></div>
</div>
<div class="external" id="external-11"><p>I am the first external</p></div>
<div class="external" id="external-12"><p>I am the second external</p></div>
JAVASCRIPT:
var $ = jQuery;
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num){
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' ){
$('#cont-'+num).fadeIn();
}else{
$('#cont-'+num).fadeOut();
}
}
CSS:
.content{
background:green;
color:white;
padding:5px;
}
.external{
background:blue;
color:white;
padding:5px;
}
.content, .external, .child{
display:none;
}
.active{
display:block;
}
CodePen: http://codepen.io/anon/pen/uFpzE
What I'm trying to achieve is this:
If you click on #tab-3 the .external div that corresponds with the first child of #cont-3 should show.
I've tried this:
var $ = jQuery;
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
var random = $('#cont'+num + '.child:first-child').attr('id').replace(/child-/, '');
});
function showCont(num){
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none'){
$('#cont-'+num).fadeIn();
$('#external'+random).fadeIn({'duration':600,'queue':false});
}else{
$('#cont-'+num).fadeOut();
}
}
...and it isn't working. Where am I going wrong?
I'm not 100% sure what you're trying to accomplish with the code in the document.ready part, but the showCont function does what you requested.
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num)
{
$('.content').fadeOut(300);
$('.external').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' )
{
$('#cont-'+num).fadeIn();
// get the child element's id
var targetID = $("#cont-"+num).children().first().attr('id');
if(targetID)
{
// construct the id of the external element
$('#external-'+targetID.substring(targetID.indexOf('-')+1))
.fadeIn({'duration':600,'queue':false});
}
}
else
{
$('#cont-'+num).fadeOut();
}
}
DEMO
The variable random is not defined in your JS file, and there are some typos regarding the selector elements (e.g. it should be $('#external-'+random) instead of $('#external'+random)). Base on your code, I came up with the following for your reference:
DEMO
var $ = jQuery;
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num){
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' )
{
$('#cont-'+num).fadeIn();
var random = $('#cont-'+num + ' div:first-child').attr('id').substring(6);
$('#external-'+random).fadeIn({'duration':600,'queue':false});
}
else
{
$('#cont-'+num).fadeOut();
var random = $('#cont-'+num + ' div:first-child').attr('id').substring(6);
$('#external-'+random).fadeOut({'duration':600,'queue':false});
}
}
I think you've got random in the wrong function. The #cont and #external selectors are also missing a trailing dash:
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num){
var random = $('#cont-'+num + '.child:first-child').attr('id').replace(/child-/, '');
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none'){
$('#cont-'+num).fadeIn();
$('#external-'+random).fadeIn({'duration':600,'queue':false});
}else{
$('#cont-'+num).fadeOut();
}
}
This should be closer to what you're after (untested though).
Once you've got it working, you could look at simplifying it by using data-id="num" attributes on your HTML elements and accessing the id values with .data('id') in your js, then binding the tab buttons from within your DOM ready fn. It would look closer to this:
$(function() {
$('.tab').click(function (e) {
var num = $(this).data('id'),
$child = $('.child[data-id="' + num + '"]')
;
// ...
})
})
I think this changes to your function showCont(num) would do:
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' )
{
$('#cont-'+num).fadeIn();
var value= $('#cont-'+num+' div' ).first().attr("id").slice(-2);
$('#external-'+value).fadeIn();
}
else
{
$('#cont-'+num).fadeOut();
$('.external').fadeOut();
}
I have few anchor tags inside a div and I need to retrieve the href values of all anchor tags.
For example
<div id="sample">
<ul>
<li>Location1</li>
<li>Location2</li>
<li>Location3</li>
<li>Location4</li>
</ul>
</div>
Assuming I am in /location1, the li that has a href="/location1" should have a separate background color, say for example red. If I am in /location2 the corresponding li should have the same red color.
I am trying to retrieve the page url first and then store it in a variable.
var pageurl = (window.location.pathname);
But not too sure on how to retrieve the href and then map it based on the page urls.
You do something like this:
// Get the active link first
var $links = $('#sample a').filter(function() {
return this.href && this.href == location.pathname;
});
// Highlight the current li having the link
$links.closest('li').addClass('active');
In the active class set whatever style you want to apply.
This is jQuery code, need to add jQuery library to work. It will work on page load
jQuery(document).ready(function(){
var url=document.URL.split('?')[1];
if(url == undefined){
url = '';
}
if(url != ''){
url = '#'+url;
jQuery(url).trigger('click');
}
var url=document.URL.split('?')[1];
if(url == undefined){
url = '';
}
if(url != ''){
// do here what you want to do
}
}
);
$(document).ready(function(){
$('#sample ul li a').each(function(e){
var href = $(this).attr('href');
// do something with href
});
});
I have created an html page, (template if you will) so what I would like to do is to leave the page all on it's own and use AJAX / jQuery to propagate the div elements with other external html pages.
Is this possible ?
I have been checking around and I have yet to find the solution.
Here is a snippet of my nav list...
<div>
<ul>
<li id="n-c"><span class="dir">Cosmo</span>
<ul id="switcheroo">
<li class="first">Special</li>
<li>Mineral</li>
<li>Lateral</li>
<li>Tangent</li>
</ul>
</li>
</ul>
</div>
In my content section I have added a
<div id="contentSwap"></div>
I tried this:
$("ul #switcheroo li a").click(function(event) {
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
$.get(href, function(data) {
$('#contentSwap').html(data);
});
event.preventDefault();
return false;
});
to no avail, can someone help me?
WDH
in the end I ended up using the simplest form to achieve my result.
<script type="text/javascript">
$(document).ready(function() {
$("#switcheroo").click(function(event){
$('#contentSwap2').load('pg2.html');
});
});
$(document).ready(function() {
$("#switcheroo2").click(function(event){
$('#contentSwap3').load('pg3.html');
});
});
</script>
... and so on ...
And ultimately swapping the div id with the one that had content already, instead of using an empty tag.
WDH
I appreciate all your insight #abdullah.abcoder #ShankarSangoli and #John Hartsock
When you get the html response in the get callback it will have all the tags starting from html, head body etc. Either you will have to make sure you only send the required markup from the server or parse the markup and and get only the markup that you want to append into contentSwap div.
The other approach is to use iframe, set the iframe source to href, onload of iframe find the required element, get the markup and then append it to contentSwap div.
$("ul #switcheroo li a").click(function(event) {
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
var dIf = $("#dummyIframe");
if(dIf.length == 0){
$(document.body).append('<iframe id="dummyIframe" style="display:none;"></iframe>');
dIf = $("#dummyIframe").onload(function(){
var iFrameContent = $("#dummyIframe").contents();
$('#contentSwap', window.parent.document)
.html(iFrameContent.find('#someDivIdOrAnyOtherSelector').html());
});
}
dIf[0].src = href;
event.preventDefault();
return false;
});
$("ul #switcheroo li a").click(function(event) {
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
$('#contentSwap').load('' + href + ''); //$('#contentSwap').empty().load(''+ href +''); you may use this for make your `#contantSwap` empty and then append contents to it
event.preventDefault();
return false;
});
I hope this will works
Assuming your data is HTML, then you can do the following using jQuery replaceWith():
$('#contentSwap').replaceWith(data);
Also, you may want to only import the portion of the HTML from the data by doing the following:
$('#contentSwap').replaceWith($('#somedivElement', data));